Sum of the elements of rows of matrix

lets say i have A=[1 2 1;3 2 1;3 5 4] and i want to sum up row elements separately and show me results as "Ri=..." here "i" is number of row. in this case R1=7, R2=9. R3=6.

1 Comment

It sounds like you really mean "sum up column elements". The elements you are summing all belong to a common column, not a common row.

Sign in to comment.

 Accepted Answer

Matt J
Matt J on 28 May 2014
Edited: Matt J on 28 May 2014
Asum=sum(A,1);
for i=1:length(Asum)
disp(['R' num2str(i) '=' num2str(Asum(i))]);
end

4 Comments

Hi Matt, thanks for answer..but it is now working.
This code hurts, Matt J ;-)
Hurts in what way? As you recommended, I do not autogenerate separate variables R1, R2, R3,...
:-) Indeed, you exactly did what Akmyrat asked for ...

Sign in to comment.

More Answers (2)

sum(A')

2 Comments

Matt J
Matt J on 28 May 2014
Edited: Matt J on 28 May 2014
This won't work if A is a row vector. Transposing is also expensive in computation time and memory if A is large.
Please let us know what is best way to do this?

Sign in to comment.

You do not want to store the results in separate variables R1, R2, etc., but rather as elements of a single variable R, with R(1), R(2), etc.
A = magic(3)
RowSum = sum(R,2)
help sum

2 Comments

Hi jos, thanks. but sorry your code also not working.
What do you mean, "not working"? Did you read the help of sum?
May be you want to sum along rows rows, i.e., sum the elements in each column?
ColumnSum = sum(R,1)
Next time, be a little bit more specific ...

Sign in to comment.

Categories

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

Asked:

on 28 May 2014

Commented:

on 29 May 2014

Community Treasure Hunt

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

Start Hunting!