How to sum up in matrix
조회 수: 3 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!