Is there a functional form in Matlab to get the same result as A{:}?
4 次查看(过去 30 天)
显示 更早的评论
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
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}{:}
"Is there a functional form in Matlab to get the same result as A{:}?"
No. Comma-separated lists are a syntax feature.
回答(1 个)
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
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'))
subsref(myfun(),substruct('{}',{':'}))
function out = myfun()
out = {1,2,3};
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dictionaries 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!