File Exchange

image thumbnail

Flatten nested cell arrays

version 1.0.0.1 (1.29 KB) by

Linearize a cell array tree structure

4.33333
3 Ratings

3 Downloads

Updated

View License

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'

Comments and Ratings (9)

Paulo Abelha

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--

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

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

I guess, this simple code is much more efficient:

result = [list{:}]

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.

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

Richie Cotton

Richie Cotton (view profile)

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.

Updates

1.0.0.1

Updated license

MATLAB Release
MATLAB 7.10 (R2010a)

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

» Watch video