Deconvolution of nested cell arrays in Matlab

by Pascal Schulthess

Recently, I faced the problem of getting heavily nested cell arrays, and since there’s no built-in function to deconvolve such cell array, I had to find another solution.

If you have a nested array nestedArray which is defined as

nestedArray = {{'a','b'},'c'};

and you want to flatten it in way that it looks like

flatArray = {'a','b','c'};

you need to write a short function which looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function flatArray = flattenCell(nestedArray)
  error(nargchk(1,1,nargin));
  if ~iscell(nestedArray),
    error('Must be a cell array.');
  end
  flatArray{1} = [];
  for i=1:numel(nestedArray),
    if iscell(nestedArray{i}),
      y = flattenCell(nestedArray{i});
      [flatArray{end+1:end+length(y)}] = deal(y{:});
    else
      flatArray{end+1} = nestedArray{i};
  end
end
flatArray(1) = [];

I found this beautiful piece of code in this post in the Matlab Usenet Group.