using for loops to calculate the mean for each row and column in a matrix in matlab

To calculate the mean for each row and column in a matrix, you can use nested for loops to access each element and calculate the mean. Here's an example code snippet that shows how to do this:

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

% Calculate the mean for each row
row_mean = zeros(1, size(matrix, 1)); % Preallocate row mean array
for i = 1:size(matrix, 1)
    for j = 1:size(matrix, 2)
        row_mean(i) = row_mean(i) + matrix(i,j);
    end
    row_mean(i) = row_mean(i) / size(matrix, 2);
end
disp("Row mean: ");
disp(row_mean);

% Calculate the mean for each column
col_mean = zeros(1, size(matrix, 2)); % Preallocate column mean array
for i = 1:size(matrix, 2)
    for j = 1:size(matrix, 1)
        col_mean(i) = col_mean(i) + matrix(j,i);
    end
    col_mean(i) = col_mean(i) / size(matrix, 1);
end
disp("Column mean: ");
disp(col_mean);
674 chars
25 lines

In this example, we first create a sample matrix matrix with some values. Then, we use nested for loops to iterate through each element in the matrix and calculate the mean for each row and column. We initialize two arrays row_mean and col_mean to store the row and column means, respectively.

For each row, we first iterate through each column element and sum up the values. Then, we divide the sum by the number of column elements to get the mean for that row. Finally, we store the mean value in the row_mean array.

We do the same thing to calculate the column means, but in reverse order. We first iterate through each column element, then each row element within that column, summing up the values. Then, we divide the sum by the number of row elements to get the mean for that column. Finally, we store the mean value in the col_mean array.

At the end, we print out both the row and column means with the disp function.

gistlibby LogSnag