Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to optimize nested for loop in matlab

I have a for loop nested thrice in a matlab program. Can any of you help me optimize it.

w=5;
a = rand(m*n,10); b=rand(m,n);
for i = 1 : m
   for j = 1 : n
      for k = 1 : l
         if (i-w >= 1 && i+w <= m)
             featureL = a(((i-1)*n)+j,:); featureR = a(((i-1)*n)+j-d,:);
             D1(i,j,k) = sqrt( sum( (featureL - featureR) .* (featureL - featureR) ) );
             D2(i,j,k) = mean2( b(i-w:i+w, j-w:j+w) );
         end
      end
   end
end

I know the performance could be heavily improved by using meshgrid, but I am not sure how to do it.

Thanks in anticipation.

Can it be done something like this..

[X Y Z] = meshgrid(1:m,1:n,1:l);
D1(something containing X,Y,Z) = sqrt( sum( ( a(something cont. X,Y) - a(something cont. X,Y)).*(a(something cont. X,Y) - a(something cont. X,Y)) ) );
% similarly D2

Thanks a lot!.

like image 631
rdg Avatar asked Dec 02 '25 02:12

rdg


1 Answers

I've found that a good way to attack these things is incrementally. Start by examining everything in the innermost loop, and see if it can be done at a higher level. This will reduce repeated computations.

For example, you can perform your if (i-w >= 1 && i+w <= m) two levels higher (since it only depends on i,w, and m), reducing if checks and skipping loop iterations. Once that is done, your featureL and featureR calculations can be moved up one level; they are performed inside the k loop but only depend on j. Similarly, sqrt( sum( (featureL - featureR) .* (featureL - featureR) ) ) can be computed outside of the k loop, put into a variable, and assigned later.

In fact, as far as I can see you can get rid of the entire k loop since k is never used. Here's your code with some of this applied:

w=5; 
a = rand(m*n,10); 
b=rand(m,n); 
for i = 1 : m
    if (i-w >= 1 && i+w <= m)
        for j = 1 : n
            featureL = a(((i-1)*n)+j,:); 
            featureR = a(((i-1)*n)+j-d,:);
            x = sqrt( sum( (featureL - featureR) .* (featureL - featureR) ) );
            y = mean2( b(i-w:i+w, j-w:j+w) )           
            D1(i,j,:) = x;              
            D2(i,j,:) = y;
        end    
    end 
end
like image 85
goric Avatar answered Dec 06 '25 07:12

goric