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

Flatten nested cell arrays



Linearize a cell array tree structure

| Watch this File

File Information

 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)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (6)
26 Oct 2013 L. Hare Duncare

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));
Ctemp = flatten(A{i});
C = cat(2, C, Ctemp);

02 Nov 2012 Alexander Kosenkov

I guess, this simple code is much more efficient:

result = [list{:}]

20 May 2011 David Goldsmith

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.

20 May 2011 David Goldsmith

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

26 Jul 2010 Richie Cotton  
23 Jul 2010 Manu Raghavan

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

Contact us