How to unnest cell arrays using a for loop?

14 views (last 30 days)
A = [{{{{4}}}}, {0}, {{1}}, {{{0}}}]
I need to unnest the cell array so I am left with just the numbers in a vector. [4 0 1 0]
I think you can use a for loop..
How do I do this?

Accepted Answer

Jan
Jan on 10 Mar 2019
Edited: Jan on 11 Mar 2019
A = [{{{{4}}}}, {0}, {{1}}, {{{0}}}]
B = zeros(size(A));
for iA = 1:numel(A)
a = A{iA};
while iscell(a)
a = a{1};
end
B(iA) = a;
end
Or:
c = true;
while any(c)
c = cellfun('isclass', A, 'cell');
A(c) = cellfun(@(x) x, A(c));
end
B = [A{:}]

More Answers (0)

Community Treasure Hunt

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

Start Hunting!