Unnest cell array with nested cells to a cell array

218 ビュー (過去 30 日間)
Federico Canè 2014 年 10 月 20 日
コメント済み: Simon Matte 2020 年 10 月 12 日
How do I expand out an array with dimension '<100x1 cell>' in which each cell has a dimension '<1x11 cell>' into an array with dimension '<100x11 cell>'. Surely this must be straightforward? Thx

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

採用された回答

Sean de Wolski 2014 年 10 月 20 日
% Sample Data
C = repmat({num2cell(1:11,1)},100,1);
% Unpacked
C2 = vertcat(C{:})
Unpack ( {:} ) it and use comma-separated list expansion in vertcat.
3 件のコメント1 件の古いコメントを表示1 件の古いコメントを非表示
Boris 2017 年 7 月 29 日
Doesn't appear to work if the cell array contains cell arrays of empties ([]). Gives a single 1 column vertical cell array with most (but crucially not all) the elements......
Im my case, mycellarray has 1 x 26 cell array. Each of these cell arra6 has 709 by 1 cells. Several of these cell arrays are empty, some are partially empty. vertcat --> a cell array with 17018 x 1 cells, each with a single entry (many blank). However, 26*709 is 18434, not 17018...
Furthermore, if I transpose mycellarray (26 x 1 cells) then vertcat, I get the same result (17018 x 1 cells)... Must be hitting some kind of limit, I guess. Pity, as it is a pain to concatenate each cell array in mycellarray in a loop (or similar)...
Boris 2017 年 7 月 29 日

Of course, it helps if you check that all the entries in the cell array are all cell arrays!
I had two cell array entries that were themselves arrays of doubles, not cell arrays and this is what was throwing the concatenation.
However, the very simple (horizontal) concatenation given by:
myflatcellarray=[mycellarray{:}];
seems to be marginally faster than horzcat...

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

その他の回答 (2 件)

Gabor Bekes 2019 年 11 月 11 日
You might want something along the lines of:
a2 = {{'asdf',{'asdf','asdf',{'asdf'},{'asdf'},{'asdf',{'asdf'}},'asdf'},{'asdf',{'asdf'},{{'asdf'}}}},'asdf'}
while any(cellfun(@iscell,a2))
a2 = [a2{cellfun(@iscell,a2)} a2(~cellfun(@iscell,a2))];
end
Now, you need to know in advance if you have a row, column or matrix layout cell array, and you need to use vertcat() for the latter two cases (logical indexing produces columns).
1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Simon Matte 2020 年 10 月 12 日
Stumbled on this by googling a similar situation, wanted to add:
The previous solution works, but it also re-orders the elements in your cell array. Since it mattered in my specific case, I used this variant for my application:
while any(cellfun(@iscell, a2))
idx = cellfun(@iscell, a2);
a2(idx) = a2{idx};
a2(~idx) = a2(~idx);
end

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

Federico Canè 2014 年 10 月 20 日
wow, exactly what I needed. Thx

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by