How to sum up in matrix

조회 수: 3 (최근 30일)
Zhan
Zhan 2017년 4월 8일
답변: Roger Stafford 2017년 4월 8일
Assume matrix S as follows:
S = [41 105
41 85
41 35
88 575
88 40
77 10
77 125
77 105
78 10
78 15
78 335
99 90
99 20
99 30
12 45
12 45
12 130
];
I want to build a new matrix N including 4 columns:
N = [41 105 240 345
41 85 345 430
41 35 430 465
88 575 240 815
88 40 815 855
77 10 240 250
77 125 250 375
77 105 375 480
78 10 240 250
78 15 250 265
78 335 265 600
99 90 240 330
99 20 330 350
99 30 350 380
12 45 240 285
12 45 285 330
12 130 330 460
];
% Third column: The first column in matrix S is unique ID. When ID is unique, then the corresponding array in third column of matrix N should be 240. Other arrays in column 3 is calculated based on the sum of above arrays in column 2 and 3---> 345 = 105+240 &&&&&& 430 = 85 + 345 Finally the last column (4th) is sum up between second and third columns
  댓글 수: 2
Jan
Jan 2017년 4월 8일
편집: Jan 2017년 4월 8일
What have you tried so far? Can e.g. the 41 appear later in the array also? How should it be treated then?
Zhan
Zhan 2017년 4월 8일
No, 41 can't appear later. I solved in Excel using a binary code, 1 if ID changed, 0 when ID is repeated. Then simple sum function.

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

답변 (1개)

Roger Stafford
Roger Stafford 2017년 4월 8일
N = [S,zeros(size(S,1),2)];
N(1,3) = 240;
t = 240;
for k = 2:size(S,1);
if N(k,1)~=N(k-1,1)
N(k,3) = 240;
t = 240;
else
t = t + N(k-1,2);
N(k,3) = t;
end
end
N(:,4) = N(:,2) + N(:,3);

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by