Matlab

Matlab code really doesn’t like nested for-loops. I didn’t realize how much until I had written the following piece of code for an assignment:


for i=1:k
     sum_z = zeros(1,size(z,2));
     misclassified = 0;
     
     for r=1:totalSamples
         if dot(a, z(r,:)) < 0
             sum_z = sum_z + z(r,:);
             misclassified = misclassified + 1;
         end
     end
    
    a = a + sum_z;
     
     if misclassified < best_misclassified
         best_misclassified = misclassified;
         aBest = a;
     end
end

For values of k larger than 10,000 the code took several minutes to run.

I re-wrote the code and removed the inner for-loop and if statement.

for i=1:k
    tmp = bsxfun(@times, a, z);
    s = sum(tmp, 2);
    misclassified = z(find( s < 0 ),:);
    numMisclassified = size(misclassified,1);
    sum_z = sum(misclassified);
    
    a = a + sum_z;
    
    if numMisclassified < best_misclassified
        best_misclassified = numMisclassified;
        aBest = a;
    end
end

Somewhat surprisingly it now only takes seconds to run.

Tagged , . Bookmark the permalink.

Comments are closed.