필터 지우기
필터 지우기

Fastest way to convert nested cell arrays into a Matrix?

조회 수: 24 (최근 30일)
Chris Heyman
Chris Heyman 2023년 8월 9일
편집: Bruno Luong 2023년 8월 10일
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!

채택된 답변

Bruno Luong
Bruno Luong 2023년 8월 9일
편집: Bruno Luong 2023년 8월 9일
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
Bruno Luong
Bruno Luong 2023년 8월 9일
@Chris Heyman I edit the code since there is some bug
Chris Heyman
Chris Heyman 2023년 8월 10일
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]);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by