Comma separated function output requests
Mostra commenti meno recenti
The comma separated list expression A{1:0} generally produces an empty result, e.g.,
A={1,2,3};
[A{1:0}]
Therefore, I might expect both A and B below to result in empty cells, but A does not. Why is this? Is it documented somewhere?
clear A B
S=struct('type','()','subs',{{3}});
x=10:10:50;
[A{1:0}]=subsref(x,S)
[B{1:0}]=deal(x(3))
Risposta accettata
Più risposte (2)
Is this documented?
[A{1:2}] = myone(1,2,3,4) % okay
[B{1:1}] = myone(1,2,3,4) % okay
[C{1:0}] = myone(1,2,3,4) % NARGOUT==0 ... but one output is allocated.
[D{1:0}] = myone(1) % NARGOUT==0 ... but one output is allocated.
[E{1:0}] = myone() % NARGOUT==0 ... and no outputs allocated (correct).
The different behaviors of different functions seems to depend on whether the function defines output arguments internally regardless of how many outputs are actually requested (as in myone above) vs. functions that only define exactly the number of outputs that are actually requested at the output (i.e. that use nargout to specify the outputs, as in mytwo below):
[H{1:2}] = mytwo(1,2,3,4) % okay
[I{1:1}] = mytwo(1,2,3,4) % okay
[J{1:0}] = mytwo(1,2,3,4) % okay
[K{1:0}] = mytwo(1) % okay
[L{1:0}] = mytwo() % okay
function varargout = myone(varargin)
% Defines as many outputs as are provided as inputs.
varargout = varargin;
nargin
nargout
end
function varargout = mytwo(varargin)
% Defines only as many outputs as are requested.
varargout = varargin(1:nargout);
nargin
nargout
end
Why do you expect A to be the empty cell? The right hanbd side is the scalar 30:
S = struct('type', '()', 'subs', {{3}});
x = 10:10:50;
subsref(x, S)
Then:
[A{1:0}] = 30
assignes 30 to the elements of the cell array A, such that it is expanded. That [A{1:0}] on the right hand side is treated as empty is another point. You cannot mix the interpretations on the right and left side.
1 Commento
Categorie
Scopri di più su Function Definition in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!