sum different cell arrays based on index

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

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

thank you for your answer, but i realise there was a mistake in my question and now i editted it. Could you please revise your answer if possible? many thanks.
The same logic with few changes applies:
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]} ;
id = { [1,2,3], [4,5,6,7] } ;
n = length(id) ;
iwant = cell(n,1) ;
for i = 1:n
iwant{i} = sum(cat(3,A{id{i}}),3) ;
end
celldisp(iwant)
iwant{1} = 1 1 0 0 1 0 0 1 1 iwant{2} = 1 1 1 0 1 1 1 0 0

Sign in to comment.

More Answers (0)

Asked:

on 14 Sep 2021

Commented:

on 14 Sep 2021

Community Treasure Hunt

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

Start Hunting!