MATLAB Answers

sum different cell arrays based on index

1 view (last 30 days)
Sule Anjomshoae
Sule Anjomshoae on 14 Sep 2021
Commented: Stephen on 14 Sep 2021
Hello, i have
A = { [0,1,0; 0,0,0; 0,0,0],...
[1,0,0; 0,0,0; 0,1,1],...
[0,0,0; 0,1,0; 0,0,0],...
[0,0,0; 0,1,0; 0,0,0],...
[0,0,1; 0,0,0; 1,0,0],...
[1,1,0; 0,0,0; 0,0,0],...
[0,0,0; 0,0,1; 0,0,0]} ;
and i = { [1,2,3], [4,5,6,7] }
i need to sum A based on index groups resulting B={ [1,1,0; 0,1,0; 0,1,1], [1,1,1; 0,1,1; 1,0,0] }, how can i do this?
  1 Comment
Stephen
Stephen on 14 Sep 2021
F = @(x)sum(cat(3,A{x}),3);
B = cellfun(F,id,'uni',0);
celldisp(B)
B{1} = 1 1 0 0 1 0 0 1 1 B{2} = 1 1 1 0 1 1 1 0 0

Sign in to comment.

Accepted Answer

KSSV
KSSV on 14 Sep 2021
Edited: KSSV on 14 Sep 2021
A = { [0,1,0], [1,0,0], [0,0,0], [0,0,0], [0,0,1], [1,1,0], [0,0,0]} ;
id = { [1,2,3], [4,5,6] } ;
n = length(id) ;
iwant = cell(n,1) ;
for i = 1:n
iwant{i} = sum(vertcat(A{id{i}})) ;
end
celldisp(iwant)
iwant{1} = 1 1 0 iwant{2} = 1 1 1
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!