Using For Loop to find average of columns in a matrix

Hi I have a 4x365 matrix.
I'd like to know the average of the numbers in each column, so that's 365 values I'm looking for.
I can't use the mean() or sum() commands, and I'm trying to get this done using for loop.
X=ones(4,365)
cols=size(X,2);
for i=1:4
for j=1:cols
sum = sum + X(i,j);
end
end
this gives me the final iteration. I need each iteration outputted into a new matrix so I may take the average.

 Accepted Answer

Using a loop, without sum or mean:
X = randi(9,4,7)
N = size(X,1);
V = X(1,:);
for k = 2:N
V = V + X(k,:);
end
And checking:
>> X
X =
9 7 6 9 1 4 5
5 1 5 6 2 5 8
5 6 4 9 2 7 5
1 6 8 4 8 5 3
>> V/N
ans =
5.0000 5.0000 5.7500 7.0000 3.2500 5.2500 5.2500
>> mean(X,1)
ans =
5.0000 5.0000 5.7500 7.0000 3.2500 5.2500 5.2500

3 Comments

I tried your code. Instead I made X = rand(4,365). However, the output V is just 4 values.
"Instead I made X = rand(4,365). However, the output V is just 4 values."
Try the edited answer, it works for me.

Sign in to comment.

More Answers (2)

m=rand(4,365);
mean(m,1)

2 Comments

you don't need to use loop to do the above
Some assignments specifically instruct the student to use a for-loop and not the mean() command

Sign in to comment.

A = rand(4,365) ;
thesum = zeros(1,365) ;
for i = 1:4
thesum = thesum+A(i,:) ;
end
iwant = thesum/4 ;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!