Clear Filters
Clear Filters

Modifying a cell array

3 views (last 30 days)
Philipp Mueller
Philipp Mueller on 16 Feb 2021
Edited: Voss on 14 Nov 2023
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 Comment
Camille CAISSO
Camille CAISSO on 16 Feb 2021
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

Sign in to comment.

Answers (1)

Voss
Voss on 14 Nov 2023
Edited: Voss on 14 Nov 2023
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'}

Tags

Community Treasure Hunt

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

Start Hunting!