input for loop in matlab

The syntax of for loop is as follows:

main.m
for index=values
    %Statements to be executed
end
52 chars
4 lines

Where index is the loop variable that takes on each value in values in succession.

Here is an example where we will use for loop to iterate over matrix elements:

main.m
% creating a 3x4 matrix
matrix = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];

% for loop to print all elements of matrix
for i=1:size(matrix, 1)
    for j=1:size(matrix, 2)
        fprintf('matrix(%d,%d): %d\n', i, j, matrix(i,j));
    end
end
241 chars
10 lines

In the above example, we have two nested for loops. The outer loop prints the row index and the inner loop prints the column index along with the corresponding matrix value.

You can replace the fprintf statement with any desired code block to execute inside the loop.

related categories

gistlibby LogSnag