Simple explanation - how to use varargout
43 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Can anyone give me a simple example of how to use the varargout function? I can't seem to get it to work. The code I've tried looks like this:
[varargout]=fxn_name(x)
if condition, varargout(1)={P}, end
if condition 2, varargout(2)={Q}, end
I tried the above code and the output is always the last calculation that was made in the function file. (ex. the output is ans=N, if N was the last value to be evaluated in the function file).
I've tried reading some of the examples on the web but I can't make heads or tails out of them. Thanks for any help.
0 commentaires
Réponse acceptée
Matt Fig
le 15 Oct 2012
Modifié(e) : Matt Fig
le 15 Oct 2012
Try this:
function varargout = varargoutexample(x)
% Demonstrates how to use VARAGOUT.
% Pass in a vector of values.
% Note that NARGOUT is the number of output
% arguments you called the function with.
for ii = 1:nargout
varargout{ii} = x.^ii;
end
Now from the command line, call the function with a different number of output arguments:
A = varargoutexample(0:.25:1);
[A,B] = varargoutexample(0:.25:1)
[A,B,C,D] = varargoutexample(0:.25:1)
or we can have a little fun:
x = 0:.01:1;
S(1:2:20) = {x};
[S{2:2:20}] = varargoutexample(x);
plot(S{:}) % Plot x^1, x^2, x^3.... x^10
Basically, each element of the cell array varargout holds the value returned to the corresponding output argument you requested when you called the function. So if you ask for two output arguments, varargout{1} holds the first output argument and varargout{2} holds the second, etc.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!