Modifying a cell array

1 回表示 (過去 30 日間)
Philipp Mueller
Philipp Mueller 2021 年 2 月 16 日
編集済み: Voss 2023 年 11 月 14 日
Hello,
I have a cell array which is called hhh.
Elements of hhh could be:
hhh{1, 44} -> 'Rog'
hhh{1, 167}{1, 1} -> 'Rog'
hhh{1, 167}{1, 2} -> 'CvF'
I would like to turn entries that contain cells-within-cells, such as:
hhh{1, 167}{1, 1} -> 'Rog'
hhh{1, 167}{1, 2} -> 'CvF'
Into:
hhh{1, 167}-> 'Ro'
hhh{1, 168}-> 'CvF'
FYI:maximum nesting level is 2
How can I achieve these two goals? Thx in advance.
  1 件のコメント
Camille CAISSO
Camille CAISSO 2021 年 2 月 16 日
Hi,
Clearly not the most efficient way to do it but it works :
clear all
close all
hhh{1, 1}{1, 1} ='a';
hhh{1, 2}{1, 1} ='b';
hhh{1, 2}{1, 2} ='c';
hhh{1, 3}{1, 1} ='d';
hhh{1, 3}{1, 2} ='e';
hhh{1, 3}{1, 3} ='f';
hhh{1, 4}{1, 1} ='g';
hhh_2 = {};
count = 0;
for i =1:size(hhh,2)
A = size(hhh{i},2);
if A>1
for k=1:A
hhh_2{1,count+k} = hhh{1,i}{1,k};
end
else
hhh_2{1,count+1} = hhh{1,i};
end
count = count + A;
end
Yeah it's dirty, unefficient and slow.
Works on R2020a
Cheers,
Camille

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

回答 (1 件)

Voss
Voss 2023 年 11 月 14 日
編集済み: Voss 2023 年 11 月 14 日
If any cell array contained in a cell of hhh can only be a row vector, then:
hhh = {'a',{'b','c'},{'d','e','f'},{'g'}}
hhh = 1×4 cell array
{'a'} {1×2 cell} {1×3 cell} {1×1 cell}
idx = cellfun(@iscell,hhh);
hhh(~idx) = num2cell(hhh(~idx));
hhh = [hhh{:}]
hhh = 1×7 cell array
{'a'} {'b'} {'c'} {'d'} {'e'} {'f'} {'g'}
If any cell array contained in a cell of hhh can be of arbitrary size, then:
hhh = {'a',{'b';'c'},{'d','e','f'},{'g'}}
hhh = 1×4 cell array
{'a'} {2×1 cell} {1×3 cell} {1×1 cell}
idx = cellfun(@iscell,hhh);
hhh(~idx) = num2cell(hhh(~idx));
hhh(idx) = cellfun(@(x)x(:),hhh(idx),'UniformOutput',false);
hhh = vertcat(hhh{:}).'
hhh = 1×7 cell array
{'a'} {'b'} {'c'} {'d'} {'e'} {'f'} {'g'}

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by