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

2 Ansichten (letzte 30 Tage)
marcus
marcus am 9 Nov. 2023
Bearbeitet: Stephen23 am 9 Nov. 2023
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 Kommentar
Stephen23
Stephen23 am 9 Nov. 2023
Bearbeitet: Stephen23 am 9 Nov. 2023
"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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 9 Nov. 2023
Bearbeitet: Stephen23 am 9 Nov. 2023
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

Kategorien

Mehr zu Performance and Memory finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by