Modifying a cell array
6 views (last 30 days)
Show older comments
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
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
Answers (1)
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'}}
idx = cellfun(@iscell,hhh);
hhh(~idx) = num2cell(hhh(~idx));
hhh = [hhh{:}]
If any cell array contained in a cell of hhh can be of arbitrary size, then:
hhh = {'a',{'b';'c'},{'d','e','f'},{'g'}}
idx = cellfun(@iscell,hhh);
hhh(~idx) = num2cell(hhh(~idx));
hhh(idx) = cellfun(@(x)x(:),hhh(idx),'UniformOutput',false);
hhh = vertcat(hhh{:}).'
0 Comments
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!