Info

This question is closed. Reopen it to edit or answer.

How to build a new matrix based on some available information

1 view (last 30 days)
Assume matrix E as follows:
E = [
1 260 120
1 340 60
1 455 300
1 555 60
2 620 120
2 705 60
2 720 360
2 1025 60
2 1045 60
3 1130 60
3 1345 60
3 1375 60
];
Based on the unique ID (column one) and sum up of second and third columns of matrix E, I want to create a new matrix D.
D = [
1 260 120 260
1 340 60 380
1 455 300 440
1 555 60 740
2 620 120 620
2 705 60 740
2 720 360 800
2 1025 60 1160
2 1045 60 1220
3 1130 60 1130
3 1345 60 1190
3 1375 60 1250
];
% D(1,4) = D(1,2)
% D(2,4) = D(1,4) + D(1,3)
% D(3,4) = D(2,4) + D(2,3)
% D(4,4) = D(3,4) + D(3,3)
% D(5,4) = D(5,2) %because ID is changed then we should reset number D(5,2) = D(5,4)
% D(6,4) = D(5,2) + D(6,3)
.
.
.
  2 Comments
Akira Agata
Akira Agata on 22 May 2017
Let me clarify.
You mentioned that D(2,4) = D(1,4) + D(2,3). But looking at the matrix D you provided, it seems that D(2,4) = D(1,4) + D(1,3), and D(3,4) = D(2,4) + D(2,3), and so forth.
Alex Rob
Alex Rob on 22 May 2017
@Akira Agata Thank you. I corrected them in the question.

Answers (3)

the cyclist
the cyclist on 22 May 2017
This is straightforwardly accomplished with a simple for loop:
E = [
1 260 120
1 340 60
1 455 300
1 555 60
2 620 120
2 705 60
2 720 360
2 1025 60
2 1045 60
3 1130 60
3 1345 60
3 1375 60
];
nrows = size(E,1);
E3 = zeros(nrows,1);
E3(1) = E(1,2);
for nr = 2:nrows
if E(nr,1)==E(nr-1,1)
E3(nr) = E3(nr-1) + E(nr-1,3);
else
E3(nr) = E(nr,2);
end
end
D = [E,E3]

Akira Agata
Akira Agata on 25 May 2017
Let me post an alternative solution:
E = [
1 260 120
1 340 60
1 455 300
1 555 60
2 620 120
2 705 60
2 720 360
2 1025 60
2 1045 60
3 1130 60
3 1345 60
3 1375 60
];
C = zeros(size(E,1), 1);
[G, ID] = findgroups(E(:, 1));
for kk = 1:numel(ID)
idx = G == ID(kk);
temp = [E(find(idx, 1), 2); E(find(idx, nnz(idx)-1), 3)];
C(idx) = cumsum(temp);
end
D = [E, C];

Andrei Bobrov
Andrei Bobrov on 25 May 2017
E = [
1 260 120
1 340 60
1 455 300
1 555 60
2 620 120
2 705 60
2 720 360
2 1025 60
2 1045 60
3 1130 60
3 1345 60
3 1375 60
];
D = E;
ii = find([true;diff(E(:,1)) ~= 0]);
D(:,4) = [0;D(1:end-1,3)];
D(ii,4) = D(ii,2);
add = accumarray(D(:,1),D(:,4));
D(ii(2:end),4) = D(ii(2:end),4) - add(1:end-1);
D(:,4) = cumsum(D(:,4));

This question is closed.

Community Treasure Hunt

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

Start Hunting!