Concatenate elements of cell arrays vertically

50 views (last 30 days)
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?
  3 Comments
Stephen23
Stephen23 on 18 Jan 2022
B = vertcat(b) % <- does nothing
Preallocated b followed by a FOR loop is probably the most efficient approach.
Sim
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{:});

Sign in to comment.

Accepted Answer

KSSV
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 Comments
Sim
Sim on 17 Jan 2022
Thanks a lot @KSSV!
This solution works well for me :)
However, I have noticed that this solution is slightly slower then the traditional loop for.... strange :)
tic
iwant = cell2mat(cellfun(@(x) x(1,:),A,'UniformOutput',false));
toc
tic
for i = 1 : size(A,1)
b{i} = A{i}(1,:);
end
iwant = vertcat(b{:});
toc
% solution with cellfun
Elapsed time is 0.000518 seconds.
% solution with the traditional loop for
Elapsed time is 0.000197 seconds.
Also for my case, which is bigger than A, the traditional loop for is faster...
% solution with cellfun
Elapsed time is 0.012030 seconds.
% solution with the traditional loop for
Elapsed time is 0.005301 seconds.
KSSV
KSSV on 18 Jan 2022
Yes you are right. cellfun would be slow comapred to loop.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!