Sum of the elements of rows of matrix

조회 수: 17 (최근 30일)
Akmyrat
Akmyrat 2014년 5월 28일
댓글: Jos (10584) 2014년 5월 29일
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
Matt J
Matt J 2014년 5월 28일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2014년 5월 28일
편집: Matt J 2014년 5월 28일
Asum=sum(A,1);
for i=1:length(Asum)
disp(['R' num2str(i) '=' num2str(Asum(i))]);
end
  댓글 수: 4
Matt J
Matt J 2014년 5월 28일
Hurts in what way? As you recommended, I do not autogenerate separate variables R1, R2, R3,...
Jos (10584)
Jos (10584) 2014년 5월 29일
:-) Indeed, you exactly did what Akmyrat asked for ...

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Chandrasekhar
Chandrasekhar 2014년 5월 28일
sum(A')
  댓글 수: 2
Matt J
Matt J 2014년 5월 28일
편집: Matt J 2014년 5월 28일
This won't work if A is a row vector. Transposing is also expensive in computation time and memory if A is large.
Chandrasekhar
Chandrasekhar 2014년 5월 28일
Please let us know what is best way to do this?

댓글을 달려면 로그인하십시오.


Jos (10584)
Jos (10584) 2014년 5월 28일
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
Akmyrat
Akmyrat 2014년 5월 28일
Hi jos, thanks. but sorry your code also not working.
Jos (10584)
Jos (10584) 2014년 5월 28일
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 ...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by