Code covered by the BSD License

### Highlights from Flatten nested cell arrays

5.0
5.0 | 2 ratings Rate this file 6 Downloads (last 30 days) File Size: 1.29 KB File ID: #27009

# Flatten nested cell arrays

### Manu Raghavan (view profile)

Linearize a cell array tree structure

File Information
Description

C1 = flatten({{1 {2 3}} {4 5} 6})
C2 = flatten({{'a' {'b','c'}} {'d' 'e'} 'f'})

% Outputs:
C1 =
[1] [2] [3] [4] [5] [6]
C2 =
'a' 'b' 'c' 'd' 'e' 'f'

MATLAB release MATLAB 7.10 (R2010a)
26 Oct 2013 L. Hare Duncare

### L. Hare Duncare (view profile)

Doesn't work if your cell array has function handles in it.

>> C1 = flatten({{1 {2 3}} 'f' {'e' 'g'} {4 @isempty 5} 6})
Error using horzcat

Here's the fixed code (using `cat` for slight performance bump):
C = {};
for i = 1:numel(A)
if ~iscell(A{i})
C = cat(2, C, A(i));
else
Ctemp = flatten(A{i});
C = cat(2, C, Ctemp);
end
end

02 Nov 2012 Alexander Kosenkov

### Alexander Kosenkov (view profile)

I guess, this simple code is much more efficient:

result = [list{:}]

Comment only
20 May 2011 David Goldsmith

### David Goldsmith (view profile)

Never mind, just answered my own ?: you lose all the field keys! Plus, struct2cell isn't recursive, so it only flattens the top of the tree. Still, it gives me something to start from. If I can write something that works robustly, I'll post it.

Comment only
20 May 2011 David Goldsmith

### David Goldsmith (view profile)

Has anyone used this w/ struct2cell to flatten nested structs? Any surprises/non-intuitive behaviors observed?

Comment only
26 Jul 2010 Richie Cotton

### Richie Cotton (view profile)

23 Jul 2010 Manu Raghavan

### Manu Raghavan (view profile)

You can use this function to flatten the output from Bloomberg's unordered BLP interface in the Datafeed Toolbox.

Comment only