Fastest way to convert nested cell arrays into a Matrix?

21 views (last 30 days)
I have a set of cell arrays of size 1000x1
Each element of one of these cell arrays is a cell of size 1806x1
Each element of the nested 1806x1 cells is a matrix of doubles of size 8x1
For a given cell array, I would like to create a 1000x1806x8 matrix of the contained values.
For some cell arrays, I had needed to check on data as it was extracted with conditional statements, so I used nested loops. However, for the rest of my data, I just to extract/convert the data as fast as possible.
A consistent order of the data needs to be maintained (IE it should be 1000 of 1806x8 organized in the same fashion across all 1000 rows).
I currently have something like the following:
%Initialize
A_Length=length(ExampleCellArray);
B_Length=length(ExampleCellArray{1, 1});
C_Length=length(ExampleCellArray{1, 1}{1,1});
OutputMatrix=zeros([A_Length,B_Length,C_Length])+NaN ;
%Extract
for A=1:A_Length
for B=1:B_Length
for C=1:C_Length
OutputMatrix(A,B,C)=ExampleCellArray{A, 1}{B,1}(C);
end
end
end
What is the fastest (and most efficient) way to convert my data to matrix form?
I've done some searching but there seems to be a few methods and I’m not sure which is fastest. Also, I don’t see any specific examples which include nested cells like this.
…Yes, this is a horrible implementation of nested cells but it's the form I have and thus I want to convert the data to matrices before further manipulations.
Bonus question: Why does the a parallelized version (IE parfor A=1:A_Length ) of the above example run more slowly than a traditional for loop?
Thanks!

Accepted Answer

Bruno Luong
Bruno Luong on 9 Aug 2023
Edited: Bruno Luong on 9 Aug 2023
If the deep nested arrays are column vectors
Tmp=cat(2,ExampleCellArray{:})';
OutputMatrix=reshape(cat(2,Tmp{:})', [A_Length B_Length C_Length]);
If the deep nested arrays are row vectors
Tmp=cat(2,ExampleCellArray{:})';
OutputMatrix=reshape(cat(1,Tmp{:}), [A_Length B_Length C_Length]);
  3 Comments
Chris Heyman
Chris Heyman on 10 Aug 2023
Beautiful! The latest version has it down to ~0.5 seconds!
Tmp=cat(2,ExampleCellArray{:})';
OutputMatrix=reshape(cat(2,Tmp{:})', [A_Length B_Length C_Length]);

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!