필터 지우기
필터 지우기

Sum the values of an matrix

조회 수: 2 (최근 30일)
luca
luca 2019년 8월 5일
편집: luca 2019년 8월 5일
Hi ,
given a matrix
SU = [1 0 1 0 1 0 1 1 1 0 1 0 0;
0 0 0 1 1 0 0 1 0 1 0 0 0;
1 1 1 0 0 0 0 0 1 1 1 0 0]
I want to assign the value 6 to all the 1 of the first raw, 3 to all the 1 of the second raw, 2 to all the 1 of the third raw. Obtaining:
SU = [6 0 6 0 6 0 6 6 6 0 6 0 0;
0 0 0 3 3 0 0 3 0 3 0 0 0;
2 2 2 0 0 0 0 0 2 2 2 0 0]
Then I want to create a vector B that contain the sum of all the column. for example, the first element of B should be equal to 6+0+2=8. Obtaining
B = [8 2 8 3 9 0 6 9 8 5 8 0 0]
Does someone help me to write this code?
Thanks
  댓글 수: 1
Adam Danz
Adam Danz 2019년 8월 5일
1) SU is a matrix, not a vector.
2) I think you meant to assign a value of 2 to the third column, not 3, based on the B summation.

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

채택된 답변

Adam Danz
Adam Danz 2019년 8월 5일
편집: Adam Danz 2019년 8월 5일
% SU Matrix
SU = [1 0 1 0 1 0 1 1 1 0 1 0 0;
0 0 0 1 1 0 0 1 0 1 0 0 0;
1 1 1 0 0 0 0 0 1 1 1 0 0];
% Replace 1 with 6,3,2 in 1st, 2nd, 3rd rows respectively
% This assumes all values in SU are either 1 or 0.
SU = SU .* [6;3;2];
% If the above assumption is incorrect use this line instead.
% SU = (SU==1) .* [6;3;2]
% Sum columns
B = sum(SU,1)

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by