Concatenate elements of cell arrays vertically

51 ビュー (過去 30 日間)
Sim
Sim 2022 年 1 月 17 日
コメント済み: Sim 2022 年 1 月 18 日
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 件のコメント
Stephen23
Stephen23 2022 年 1 月 18 日
B = vertcat(b) % <- does nothing
Preallocated b followed by a FOR loop is probably the most efficient approach.
Sim
Sim 2022 年 1 月 18 日
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
KSSV 2022 年 1 月 17 日
編集済み: KSSV 2022 年 1 月 17 日
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 件のコメント
Sim
Sim 2022 年 1 月 17 日
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 2022 年 1 月 18 日
Yes you are right. cellfun would be slow comapred to loop.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by