MATLAB Language MATLAB Best Practices Avoid loops


Example

Most of the time, loops are computationally expensive with Matlab. Your code will be orders of magnitudes faster if you use vectorization. It also often makes your code more modular, easily modifiable, and easier to debug. The major downside is that you have to take time to plan the data structures, and dimension errors are easier to come by.

Examples

Don't write

for t=0:0.1:2*pi
    R(end+1)=cos(t);
end

but

t=0:0.1:2*pi;
R=cos(t)

Don't write

for i=1:n
    for j=1:m
        c(i,j)=a(i)+2*b(j);
    end
end

But something similar to

c=repmat(a.',1,m)+2*repmat(b,n,1)

For more details, see vectorization