Convert cell-array to array-of-cells, for array-of-struct creation?

조회 수: 5 (최근 30일)
Bjoern
Bjoern 2014년 6월 17일
댓글: Bjoern 2014년 6월 19일
Hi, how can I convert a cell-array to an array-of-cells?
I have (following a file textscan) a cell array of format:
Fr = [{uint8([1;2;3])}, {uint32([4;5;6])}, {[7;8;9]}]
And need to get to this array of cells:
To = [{Fr{1,1}(1), Fr{1,2}(1), Fr{1,3}(1)} ;...
{Fr{1,1}(2), Fr{1,2}(2), Fr{1,3}(2)} ;...
{Fr{1,1}(3), Fr{1,2}(3), Fr{1,3}(3)}]
..without having to loop (Fr can be large) through Fr.
The reason is that I want an array-of-struct, rather than struct-of-array. Reference:
Incorrect = cell2struct(Fr,{'f1','f2','f3'},2)
Correct = cell2struct(To,{'f1','f2','f3'},2)

채택된 답변

Andrei Bobrov
Andrei Bobrov 2014년 6월 18일
Fr = [{uint8([1;2;3])}, {uint32([4;5;6])},...
{[7;8;9]}, {uint8([11,12;13,14;15,16])}];
To = cellfun(@(x)num2cell(x,2),Fr,'un',0);
out = [To{:}];
  댓글 수: 6
Azzi Abdelmalek
Azzi Abdelmalek 2014년 6월 18일
Sorry Andrei, I didn't read completly the explanation given by Bjoern. There is no doubt about your result, I misunderstood the new question.
Bjoern
Bjoern 2014년 6월 19일
Excellent, thanks a lot! Just FYI for other users:
This proposal is about 60% quicker than Cedric's proposal. Both produced the same result :)

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

추가 답변 (2개)

Cedric
Cedric 2014년 6월 17일
To = cellfun( @(cc)num2cell(cc), Fr, 'UniformOutput', false ) ;
To = [To{:}] ;
  댓글 수: 6
Cedric
Cedric 2014년 6월 18일
See Andrei's answer, NUM2CELL can take a second "dim" argument and I didn't know that!

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


Azzi Abdelmalek
Azzi Abdelmalek 2014년 6월 17일
편집: Azzi Abdelmalek 2014년 6월 17일
To=num2cell([Fr{:}])
  댓글 수: 4
Bjoern
Bjoern 2014년 6월 17일
Thanks once again! Please see the comment (for Cedric) on me missing to mention an important fact. It looks like your proposal removes the last column.
Azzi Abdelmalek
Azzi Abdelmalek 2014년 6월 18일
Fr = [{uint8([1;2;3])}, {uint32([4;5;6])},...
{[7;8;9]}, {uint8([11,12;13,14;15,16])}]
mm=cellfun(@(x) size(x,2),Fr)
nn=1:numel(mm)
r=size(Fr{1},1)
dd=cell2mat(arrayfun(@(x,y) [1:x;y*ones(1,x)],mm,nn,'un',0))
[i1,j1]=meshgrid(dd(1,:),1:r)
[i2,j2]=meshgrid(dd(2,:),1:r)
out=arrayfun(@(x,y,z) Fr{x}(y,z),i2,j1,i1,'un',0)

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

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by