using for loops calculate the mean for rows and columns of a matrix in matlab

To calculate the mean for rows and columns of a matrix, you can use for loops in MATLAB. The following code demonstrates how to calculate the mean for rows and columns of a matrix using for loops:

main.m
% create an example matrix
M = [1 2 3; 4 5 6; 7 8 9];

% calculate the mean for rows using for loop
mean_rows = zeros(1, size(M,1));
for i = 1:size(M,1)
    mean_rows(i) = mean(M(i,:));
end

% calculate the mean for columns using for loop
mean_columns = zeros(1, size(M,2));
for i = 1:size(M,2)
    mean_columns(i) = mean(M(:,i));
end

% print the results
fprintf('Mean for rows: ');
disp(mean_rows);
fprintf('Mean for columns: ');
disp(mean_columns);
452 chars
21 lines

In this code, we first create an example matrix M. We then calculate the mean for rows using a for loop that iterates over each row of the matrix. The mean() function is used to compute the mean of each row. The mean values are stored in a row vector mean_rows.

Similarly, we compute the mean of each column by iterating over each column of the matrix using a for loop. The mean() function is used to compute the mean of each column. The mean values are stored in a row vector mean_columns.

Finally, we print the results using the fprintf() and disp() functions.

gistlibby LogSnag