Concatenate elements of cell arrays vertically

46 visualizaciones (últimos 30 días)
Sim
Sim el 17 de En. de 2022
Comentada: Sim el 18 de En. de 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?
  3 comentarios
Stephen23
Stephen23 el 18 de En. de 2022
B = vertcat(b) % <- does nothing
Preallocated b followed by a FOR loop is probably the most efficient approach.
Sim
Sim el 18 de En. de 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{:});

Iniciar sesión para comentar.

Respuesta aceptada

KSSV
KSSV el 17 de En. de 2022
Editada: KSSV el 17 de En. de 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 comentarios
Sim
Sim el 17 de En. de 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 el 18 de En. de 2022
Yes you are right. cellfun would be slow comapred to loop.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by