Concatenate elements of cell arrays vertically

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 commentaires

P.S.: with the loop for it would be:
for i = 1 : size(A,1)
b(i,:) = A{i}(1,:);
end
B = vertcat(b)
B = vertcat(b) % <- does nothing
Preallocated b followed by a FOR loop is probably the most efficient approach.
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{:});

Connectez-vous pour commenter.

 Réponse acceptée

KSSV
KSSV le 17 Jan 2022
Modifié(e) : KSSV le 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 commentaires

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 le 18 Jan 2022
Yes you are right. cellfun would be slow comapred to loop.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Question posée :

Sim
le 17 Jan 2022

Commenté :

Sim
le 18 Jan 2022

Community Treasure Hunt

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

Start Hunting!

Translated by