Code covered by the BSD License  

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Flatten nested cell arrays

4.3 | 3 ratings Rate this file 10 Downloads (last 30 days) File Size: 1.29 KB File ID: #27009 Version: 1.0

Flatten nested cell arrays


Manu Raghavan (view profile)


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 (7)
18 Apr 2015 Yung-Yeh

I tried c = {'',[],'1','2',{'a','b','c',{'x','y','z'},'r'},[123]}, flatten(c)but it does not work as expected.

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{:}]

Comment only
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.

Comment only
20 May 2011 David Goldsmith

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

Comment only
26 Jul 2010 Richie Cotton  
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

Contact us