Is there a functional form in Matlab to get the same result as A{:}?

조회 수: 2 (최근 30일)
marcus
marcus 2023년 11월 9일
편집: Stephen23 2023년 11월 9일
I understand this is a classic question and some aspects of it have been answered before, for instance here: How can I index a MATLAB array returned by a function without first assigning it to a local variable?
But reading through the comments it has become clear that i) some of the proposed solutions don't work anymore (the ones based on builtin or feval) or ii) don't work for certain classes or indices.
Specifically for a cell array A, the results of A{:} and subsref(A,substruct('{}',{':'})) are not the same.
For the sake of completeness, I'd like to point out that cell2mat(A) is not the same as A{:} and does not help either.
To clarify further why this is relevant, if A was just a variable there would be no need for subsref. However, if A is a more general expression such as B{1} or C(1) etc, Matlab does not let you further index it with {:}.
A minimal working example showing the problem:
A=arrayfun(@(x) rand(2,2,2),ones(3,1),'Uni',0)
cat(4,A{:})
compared to:
cat(4,subsref(arrayfun(@(x) rand(2,2,2),ones(3,1),'Uni',0),substruct('{}',{':'})))
which only works on the first element.
  댓글 수: 1
Stephen23
Stephen23 2023년 11월 9일
편집: Stephen23 2023년 11월 9일
"However, if A is a more general expression such as B{1} or C(1) etc, Matlab does not let you further index it with {:}."
B = {{1,2,3}};
B{1}{:}
ans = 1
ans = 2
ans = 3
"Is there a functional form in Matlab to get the same result as A{:}?"
No. Comma-separated lists are a syntax feature.

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

답변 (1개)

Stephen23
Stephen23 2023년 11월 9일
편집: Stephen23 2023년 11월 9일
The closest you can get is to convert the output into a structure and index into that (since R2019b) to generate a comma-separated list:
cell2struct(myfun(),'X').X
ans = 1
ans = 2
ans = 3
But I would recommend avoiding this approach: it is (in general) going to be less efficient than simply assigning to a temporary variable, harder to understand, harder to maintain, harder to debug, and requires more typing. Often when users want this kind of shortcut it appears that they are incorrectly assuming that it will be "more efficient", without really understanding how MATLAB manages data in memory.
Note that calling the function SUBSREF is not equivalent to a comma-separated list:
subsref(cell2struct(myfun(),'X'),substruct('.','X'))
ans = 1
subsref(myfun(),substruct('{}',{':'}))
ans = 1
function out = myfun()
out = {1,2,3};
end

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by