summation of matrix in column

1 visualización (últimos 30 días)
Khairul Nur
Khairul Nur el 25 de Nov. de 2019
Comentada: Andrei Bobrov el 26 de Nov. de 2019
hi, i have this final_mat (40x11), below is my code. What i trying to do is,first it will check the value of j:1 equal to j (1,2,3,4). If true, i need to sum between column in the same value of j. I tried few times but end up summation of row . and tried again until..this is my last code since fews time since morning :(
Please give me some idea how to solve this.
example of final_mat:
1 13 25 15 11 11 14 12 12 10 14
1 14 25 15 11 11 14 12 12 10 10
sum 27 50 30 22 22 28 24 24 20 24
2 13 26 14 11 11 14 12 12 13 13
2 13 25 14 12 11 14 12 12 13 13
2 13 25 14 11 11 14 12 13 13 13
3 13 24 14 11 11 14 12 12 12 14
3 13 24 14 10 11 14 12 12 13 14
for n= 1:40
for j=1:4
if final_mat(j:1)==j
for jj=2:11
sum=sum+final_mat(:,jj) % stuck here.
end
end

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 25 de Nov. de 2019
Editada: Andrei Bobrov el 25 de Nov. de 2019
final_mat = [ 1 13 25 15 11 11 14 12 12 10 14
1 14 25 15 11 11 14 12 12 10 10
2 13 26 14 11 11 14 12 12 13 13
2 13 25 14 12 11 14 12 12 13 13
2 13 25 14 11 11 14 12 13 13 13
3 13 24 14 11 11 14 12 12 12 14
3 13 24 14 10 11 14 12 12 13 14];
out = varfun(@sum,array2table(final_mat),'GroupingVariables',1)
out = out{:,[1,3:end]};
or
[i,j] = ndgrid(final_mat(:,1),1:size(final_mat,2));
out = accumarray([i(:),j(:)],final_mat(:),[],@sum);
out(:,1) = unique(final_mat(:,1));
  2 comentarios
Khairul Nur
Khairul Nur el 26 de Nov. de 2019
its run perfectly! BTW can u explain more on the code, please..
for below code, use the varfun(func,A,'GroupingVariables','Var1') use the group count.
out = varfun(@sum,array2table(final_mat),'GroupingVariables',1)
how about this one?
out = out{:,[1,3:end]};
TQ again for ur time an helpful code.
Andrei Bobrov
Andrei Bobrov el 26 de Nov. de 2019
Please read about 'Name-Value Pair Argument' - 'GroupingVariable' - may be name of variable (name of column of table) or number of column of table.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Mathematics 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