for loop for a matrix in matlab

To loop through every element of a matrix in MATLAB, you can use a combination of for loops and matrix indexing. Here is an example of how to loop through every element in a matrix and print its value:

main.m
% Create a sample matrix
matrix = [1 2 3; 4 5 6; 7 8 9];

% Get the size of the matrix
[row, col] = size(matrix);

% Loop through every element in the matrix
for i = 1:row
    for j = 1:col
        % Get the value of the current element
        val = matrix(i, j);
        
        % Print the value of the current element
        disp(val);
    end
end
354 chars
17 lines

In this example, the size function is used to get the number of rows and columns in the matrix. Then, two nested for loops are used to loop through every element in the matrix. The matrix(i, j) syntax is used to index into the matrix and get the value of the current element. Finally, the disp function is used to print the value of the current element.

related categories

gistlibby LogSnag