필터 지우기
필터 지우기

How to use cell2mat for specific elements of cell array?

조회 수: 22 (최근 30일)
gsourop
gsourop 2018년 10월 25일
편집: Stephen23 2018년 10월 25일
Hi everyone,
I am trying to create a double from specific elements of a cell array. If I have a cell array B, of dimensions 6x5, of which each element contains a double 10x4, such as:
for i = 1 : 6
for j = 1 : 5
A = randn(10,4)
B{i,j} = A;
end
end
I would like to create a big double out of all the rows and first 3 columns of B, and the second and third column of each interior double A (on this 6x3 cell array). Hence, the expected double C that should be a 60x6 matrix. I am using
C = cell2mat(B{:,1:3}(:,[2,3]));
But I get an error. What am I missing here?

채택된 답변

Stephen23
Stephen23 2018년 10월 25일
편집: Stephen23 2018년 10월 25일
C = cell2mat(B(:,1:3));
C = C(:,2:3);
"What am I missing here?"
Several things: firstly, that the B{...} syntax creates a comma-separated list from the contents of the cell array, which in general is not a valid input for cell2mat:
Secondly, that in MATLAB indexing cannot be arbitrarily added on to the end of any other expression, so you will need to use a temporary variable.
  댓글 수: 2
gsourop
gsourop 2018년 10월 25일
I think that a loop could solve the issue. Is it an efficient way to proceed?
for i =1 : 3
B1 = cell2mat(B(:,i));
B2 = B1(:,[2,3]);
if i == 1
D = B2;
else
D = [D B2]
end
end
Stephen23
Stephen23 2018년 10월 25일
편집: Stephen23 2018년 10월 25일
"Is it an efficient way to proceed?"
Not the way you are doing it, because you expand the array D on each loop iteration, which forces MATLAB to move it in memory. You should preallocate the output array and use indexing:
But ultimately you will just have to test it and find out.
Personally I would not use a loop, simply because it pointlessly obfuscates what you are doing: the time wasted trying to read/understand/maintain/reverse-engineer that loop will likely be much more than any possible gain you might get from runtime efficiency (or not). Unless this really is the slowest part of your code, you should write using the clearest syntax possible (i.e. without a loop, e.g. my answer). Why bother writing nine lines of code just to do the same thing as my two lines? This is not "efficient" coding.

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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by