using for loops find the mean of rows and columns of a matrix without using the mean command in matlab

To find the mean of rows and columns of a matrix using for loops in Matlab, we can first define a matrix and initialize variables to keep track of row and column wise sums. Then we can loop through each row and column using nested for loops, adding up the elements of each row and column as we go. Finally, we can divide the row and column wise sums by the number of elements in each row and column, respectively, to obtain their respective means.

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

% Initialize variables for row and column wise sums
rowSums = zeros(1,size(A,1));
colSums = zeros(1,size(A,2));

% Loop through each row and column, adding up the elements
for i = 1:size(A,1)
    for j = 1:size(A,2)
        rowSums(i) = rowSums(i) + A(i,j);
        colSums(j) = colSums(j) + A(i,j);
    end
end

% Divide row and column wise sums by the number of elements to obtain means
rowMeans = rowSums / size(A,2);
colMeans = colSums / size(A,1);

% Display results
disp("Row-wise means:");
disp(rowMeans);
disp("Column-wise means:");
disp(colMeans);
603 chars
25 lines

This will output:

main.m
Row-wise means:
    2    5    8
Column-wise means:
    4    5    6
67 chars
5 lines

gistlibby LogSnag