Basic Moves in MATLAB

This page provides MATLAB code snippets for common procedures in MATLAB..

Loop Over All Elements in a Vector

x = ...
for i=1:length(x)
  %  do something with x(i)
end

Loop Over All Elements in a Matrix

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

Create a Matrix (Vector) with Same Shape as an Existing Matrix (Vector)

A = ...
B = zeros(size(A));

Compute Sum of All Elements in a Vector

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

Compute Sum of All Elements in a Matrix

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