This page provides MATLAB code snippets for common procedures in MATLAB..
x = ... for i=1:length(x) % do something with x(i) end
A = ... [m,n] = size(A); % m = number of rows, n = number of columns for i=1:m for j=1:n % do something with A(i,j) end end
Instead of computing m
and n
explicitly, the two-argument
version of the size
command could be used
A = ... for i=1:size(A,1) for j=1:size(A,2) % do something with A(i,j) end end
A = ... B = zeros(size(A));
The vectorized code is
x = ... s = sum(x)
This is equivalent to
x = ... s = 0; for i=1:length(x) s = s + x(i); end
or
x = ... s = x(1); for i=2:length(x) s = s + x(i); end
The vectorized code is
A = ... s = sum(sum(A))
This is equivalent to
A = ... s = 0; [m,n] = size(A); for i=1:size(A,1) for j=1:size(A,2) s = s + A(i,j); end end