Concatenate cell array in matlab

1,445 ビュー (過去 30 日間)
Yash Khandelwal
Yash Khandelwal 2022 年 7 月 13 日
編集済み: Stephen23 2022 年 7 月 14 日
In Matlab you can concatenate arrays by saying -
a=[];
a=[a,1];
How do you do something similar with a cell array?
a={};
a={a,'abc'};
The code above keeps on nesting cells within cells. I just want to append elements to the cell array. How do I achieve this?
  1 件のコメント
Stephen23
Stephen23 2022 年 7 月 14 日
編集済み: Stephen23 2022 年 7 月 14 日
"In Matlab you can concatenate arrays by saying "
Yes, and the square bracket concatenation operator works with all types of array, not just numeric ones. Lets try:
[1,2,pi] % concatenate scalars
C1 = {1,'cat'};
C2 = {2,'hat'};
[C1;C2] % concatenate cell arrays
ans = 2×2 cell array
{[1]} {'cat'} {[2]} {'hat'}
T1 = cell2table(C1,'VariableNames',{'A','B'});
T2 = cell2table(C2,'VariableNames',{'A','B'});
[T1;T2] % concatenate tables
ans = 2×2 table
A B _ _______ 1 {'cat'} 2 {'hat'}
S1 = string(C1);
S2 = string(C2);
[S1;S2] % concatenate strings
ans = 2×2 string array
"1" "cat" "2" "hat"
... etc etc.
In contrast, using {} is not a concatenation operator, it creates a cell array. So when you used {a,'abc'} you told MATLAB to create a new cell array containing those arrays.

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

採用された回答

Anay Aggarwal
Anay Aggarwal 2022 年 7 月 13 日
編集済み: Anay Aggarwal 2022 年 7 月 13 日
Hi Yash
I have an understanding that you want to concatenate array.
If a and b are cell arrays, then you concatenate them in the same way you concatenate other arrays: using []:
>> a={1,'f'}
a =
1×2 cell array
{[1]} {'f'}
>> b={'q',5}
b =
1×2 cell array
{'q'} {[5]}
>> [a,b]
ans =
1×4 cell array
{[1]} {'f'} {'q'} {[5]}
To append a single element, you can do a{end+1}=1 or a(end+1)={1}.
Hope this helps
Regards

その他の回答 (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