Summation column matrix using for loop
39 views (last 30 days)
Show older comments
Shiela Harkhoe
on 5 Nov 2015
Answered: Ursala Waqar
on 10 Oct 2018
Hi, I have a question. For my homework I have a 4x5 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.
0 Comments
Accepted Answer
Star Strider
on 5 Nov 2015
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);
2 Comments
Star Strider
on 5 Nov 2015
Shiela Harkhoe’s ‘Answer’ became this Comment:
I know that. But for the assignment I need to use the 'for statement' and that's what I don't understand (the whole 'for' function).
Star Strider
on 5 Nov 2015
The for function creates an indexed loop that continues for the stated number of iterations, then stops (unless you tell it to stop earlier, but that’s a topic for another time).
I would construct your column summation loop this way:
for k1 = 1:size(A,2) % Tell ‘for’ To Iterate Over The Columns (Dimension 2)
Acolsum(k1) = sum(A(:,k1)); % Sum Column ‘k1’ And Store In ‘Acolsum(k1)’
end % End OF The Loop
More Answers (3)
Thorsten
on 5 Nov 2015
Show the number from 1 to 10
for i=1:10
i
end
Show the values of the first column of A
for i=1:size(A,1)
A(i,1)
end
Sum theses values
s = 0;
for i=1:size(A,1)
s = s + A(i,1);
end
Now you have to put this into another for loop that loops over the columns and you're done.
Shiela Harkhoe
on 5 Nov 2015
1 Comment
Star Strider
on 5 Nov 2015
The size function can take two arguments, the array and the dimension you want it to return. So in my code, size(A,2) returns the size of the second dimension (number of columns).
Your code does everything correctly, including the preallocation. Your ‘A’ matrix is not large, so if you want to see how it works as it executes, change it temporarily to add the ‘Result’ vector:
[R,C]=size(A);
X=zeros(1,C);
for c=[1:C]
for r=[1:R]
X(c)=X(c)+A(r,c);
Result = [r c X(c) A(r,c)]
end
end
Ursala Waqar
on 10 Oct 2018
A=[0:4;5:9;4,3,2,1,0;5:9];
[r,c]=size(A);
vec=zeros(1,c);
sum=0;
for i=1:c
sum=0;
for j=1:r
sum=sum+A(j,i);
vec(i)=sum;
end
end
disp(vec)
0 Comments
See Also
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!