How to sum up in matrix

3 visualizaciones (últimos 30 días)
Zhan
Zhan el 8 de Abr. de 2017
Respondida: Roger Stafford el 8 de Abr. de 2017
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 comentarios
Jan
Jan el 8 de Abr. de 2017
Editada: Jan el 8 de Abr. de 2017
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 el 8 de Abr. de 2017
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.

Iniciar sesión para comentar.

Respuestas (1)

Roger Stafford
Roger Stafford el 8 de Abr. de 2017
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);

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by