MATLAB: Summation column matrix using for loop

forfor loopmatrixsumsummation

Hi, I have a question. For my homework I have a 4×5 matrix and I'm supposed to use the for statement to find the sums of each of the columns.
I've figured it out using sum, but I don't quite understand the 'for' function. It is a loop function, but how does it work? I don't get that and therefore I'm not able to write the code for it.. Can someone explain this to me? I've read the description on this site but it didn't make me understand it.
My code using sum:
A=[0 1 2 3 4;5 6 7 8 9;4 3 2 1 0;5 6 7 8 9];
sum(A(:,1))
sum(A(:,2))
etc.

Best Answer

It’s not necessary to use a loop to take the sum of the columns, because the sum function does that by default. All you need is:
Asum = sum(A);
If you want to take the sum across the rows instead, you can do that by adding the second dimension argument:
Asumr = sum(A,2);