How to concatenate cells within cells

4 ビュー (過去 30 日間)
Keegan Sim
Keegan Sim 2023 年 5 月 12 日
編集済み: Stephen23 2023 年 5 月 12 日
Say I have X={{1},{2},{3},{4}}, Y={{5},{6},{7;8},{9;10}}
I would like to have Z={{1;5},{2;6},{3;7;8},{4;9;10}},
that is, concatenate X over Y, both 1x4 cell arrays, into Z which is also a 1x4 cell array.
Is there a simple way to do this?

採用された回答

Stephen23
Stephen23 2023 年 5 月 12 日
編集済み: Stephen23 2023 年 5 月 12 日
"Is there a simple way to do this?"
Yes, CELLFUN and VERTCAT:
X = {{1},{2},{3},{4}};
Y = {{5},{6},{7;8},{9;10}};
Z = cellfun(@vertcat,X,Y,'uni',0)
Z = 1×4 cell array
{2×1 cell} {2×1 cell} {3×1 cell} {3×1 cell}
Checking:
Z{:}
ans = 2×1 cell array
{[1]} {[5]}
ans = 2×1 cell array
{[2]} {[6]}
ans = 3×1 cell array
{[3]} {[7]} {[8]}
ans = 3×1 cell array
{[ 4]} {[ 9]} {[10]}
Note that storing numeric data in those nested cell arrays is not efficient data design. Simpler numeric arrays are intended for storing numeric data.
  2 件のコメント
Keegan Sim
Keegan Sim 2023 年 5 月 12 日
How would you store X,Y, Z and perform this operation using numeric arrays?
Stephen23
Stephen23 2023 年 5 月 12 日
編集済み: Stephen23 2023 年 5 月 12 日
"How would you store X,Y, Z and perform this operation using numeric arrays?"
Simply replace the inner nested cell arrays with basic numeric arrays:
X = {1,2,3,4};
Y = {5,6,[7;8],[9;10]};
Z = cellfun(@vertcat,X,Y,'uni',0)
Z = 1×4 cell array
{2×1 double} {2×1 double} {3×1 double} {3×1 double}
Checking:
Z{:}
ans = 2×1
1 5
ans = 2×1
2 6
ans = 3×1
3 7 8
ans = 3×1
4 9 10

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by