- 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(:));
- Subtracting a vector from each row/column of a matrix
a = [1 2 3]
b = magic(3);
c = repmat(a,3,1) - b;
- 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;
- 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
Monday, January 18, 2010
Avoid loops in Matlab
Following examples demonstrate how one can avoid for loops in MATLAB to speed up execution :
Subscribe to:
Post Comments (Atom)
1 comment:
Go through this code vectorization Guide at Matlab Support Page.
Post a Comment