File Exchange

Flatten nested cell arrays

version 1.0.0.1 (1.29 KB) by

Linearize a cell array tree structure

4.33333
3 Ratings

Updated

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'

Yung-Yeh Chang

Paulo Abelha

Paulo Abelha (view profile)

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

http://uk.mathworks.com/matlabcentral/fileexchange/58696-flatten-cell--list--

Yung-Yeh Chang

Yung-Yeh Chang (view profile)

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

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

Alexander Kosenkov

Alexander Kosenkov (view profile)

I guess, this simple code is much more efficient:

result = [list{:}]

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.

David Goldsmith

David Goldsmith (view profile)

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

Richie Cotton

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.