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 CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by