# Concatenate elements of cell arrays vertically

13 views (last 30 days)
Sim on 17 Jan 2022
Commented: Sim on 18 Jan 2022
Hi I have a 3x1 cell array, where each cell contains a 2x8 double matrix:
A = {[8 9 0 0 1 0 1 0; 5 3 0 0 1 1 1 1];
[2 4 0 0 0 0 1 0; 3 9 0 1 0 0 0 1];
[6 2 1 1 1 0 1 1; 9 7 1 1 0 0 0 0]};
I would like to concatenate vertically the first matrix's rows in each cell and get this 3x8 double matrix:
B =
8 9 0 0 1 0 1 0
2 4 0 0 0 0 1 0
6 2 1 1 1 0 1 1
I tried something like
vertcat(A{:}(1,:))
but it did not work obviously.
Any simple idea without any loop for?
Sim on 18 Jan 2022
Many thanks @Stephen for your suggestion !
Yes, sorry, this works:
for i = 1 : size(A,1)
b{i} = A{i}(1,:);
end
B = vertcat(b{:});

KSSV on 17 Jan 2022
Edited: KSSV on 17 Jan 2022
A = {[8 9 0 0 1 0 1 0; 5 3 0 0 1 1 1 1];
[2 4 0 0 0 0 1 0; 3 9 0 1 0 0 0 1];
[6 2 1 1 1 0 1 1; 9 7 1 1 0 0 0 0]};
iwant = cell2mat(cellfun(@(x) x(1,:),A,'UniformOutput',false))
iwant = 3×8
8 9 0 0 1 0 1 0 2 4 0 0 0 0 1 0 6 2 1 1 1 0 1 1
Note that cellfun uses loop inside.
##### 2 CommentsShowHide 1 older comment
KSSV on 18 Jan 2022
Yes you are right. cellfun would be slow comapred to loop.