Monday, January 18, 2010

Avoid loops in Matlab

Following examples demonstrate how one can avoid for loops in MATLAB to speed up execution :

  1. Vector assignment

    x = rand(1,100);
    %In spite of :
    for k=1:100
    y(k) = sin(x(k));
    end
    % We can use :
    y(:) = sin(x(:));


  2. Subtracting a vector from each row/column of a matrix

    a = [1 2 3]
    b = magic(3);
    c = repmat(a,3,1) - b;

  3. Use logical indexing to operate on a part of a matrix. Use "find" command wherever possible.

    a = 200:-10:50;
    % replace the value 120 by 0
    a(find(a == 120)) = 0;
    a =   200   190   180   170   160   150   140   130     0   110   100    90    80    70    60    50

    Another example :

    % [idx1, idx2] = find(angle < 0);
    % idx = [idx2 idx2];
    % for j = 1:length(idx)
    %     angle(idx(j,1),idx(j,2))=360+angle(idx(j,1),idx(j,2));
    % end
    can be replaced by following code :

    angle(angle<0) = angle(angle<0)+360;


  4. Useful commands for matrices and vectors :

    sum, norm, diff, abs, max, min, sort


     
    Useful link in this direction
    http://www.ee.columbia.edu/~marios/matlab/matlab_tricks.html  
     
     
     
     
     
     

1 comment:

Swagat said...

Go through this code vectorization Guide at Matlab Support Page.

 
pre { margin: 5px 20px; border: 1px dashed #666; padding: 5px; background: #f8f8f8; white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ }