for loops for matrix in matlab

In Matlab, we can use for loops to iterate through a matrix. There are two ways to do this: using nested for loops or vectorizing the operation.

Using nested for loops:

main.m
% Example matrix:
mat = [1 2 3; 4 5 6; 7 8 9];

% Iterate through rows:
for i = 1:size(mat, 1)
  % Iterate through columns:
  for j = 1:size(mat, 2)
    % Access each element:
    element = mat(i, j);
    % Perform operation on element:
    new_element = element + 1;
  end
end
278 chars
14 lines

Vectorizing the operation:

main.m
% Example matrix:
mat = [1 2 3; 4 5 6; 7 8 9];

% Reshape matrix into a vector:
vec_mat = reshape(mat, 1, numel(mat));

% Perform operation on vectorized matrix:
new_vec_mat = vec_mat + 1;

% Reshape vectorized matrix back into original shape:
new_mat = reshape(new_vec_mat, size(mat));
287 chars
12 lines

Vectorizing the operation can often be faster than using nested for loops, especially for large matrices, because it allows Matlab to take advantage of optimized matrix operations.

related categories

gistlibby LogSnag