use for loops in a matrix to calculate mean in matlab

Here's an example code that shows how to use a for loop to calculate the mean of each row in a matrix A in MATLAB:

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

% initialize mean matrix
mean_mat = zeros(size(A, 1), 1);

% loop through each row of matrix A
for i = 1:size(A, 1)
    % calculate mean of row i
    mean_i = mean(A(i,:));
    % store mean in mean matrix
    mean_mat(i) = mean_i;
end

% display mean matrix
disp(mean_mat);
326 chars
17 lines

In this example, we first create a matrix A with three rows and three columns. Then we create a new matrix mean_mat with the same number of rows but only one column to store the mean values.

Next, we loop through each row of matrix A using the for loop and calculate the mean of that row using the mean function in MATLAB. We then store the mean value of each row in the corresponding row of mean_mat.

Finally, we display the mean_mat matrix in the Command Window using the disp function.

Note that using a for loop to calculate the mean of each row of a matrix in MATLAB is not the most efficient way to do it. MATLAB has built-in vectorized functions that can calculate the means of each row or column of a matrix much faster than using a for loop. However, using for loops can be useful in certain situations, such as when you need to apply more complex calculations to each row or column of a matrix.

gistlibby LogSnag