Summation column matrix using for loop
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Star Strider
2015-11-5
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 个评论
Star Strider
2015-11-5
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
2015-11-5
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
更多回答(3 个)
Thorsten
2015-11-5
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
2015-11-5
1 个评论
Star Strider
2015-11-5
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
2018-10-10
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!