View 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 9 Downloads (last 30 days) File Size: 1.29 KB File ID: #27009 Version:

Flatten nested cell arrays



18 Mar 2010 (Updated )

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 (8)
13 Aug 2016 Paulo Abelha

I hav eimplemented a function which I think addresses the problems reported by Yung-Yeh and Duncare

Comment only
18 Apr 2015 Yung-Yeh

Yung-Yeh (view profile)

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

Richie Cotton (view profile)

23 Jul 2010 Manu Raghavan

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

Comment only
01 Sep 2016

Updated license

Contact us