Simple explanation - how to use varargout

43 vues (au cours des 30 derniers jours)
schwj1000
schwj1000 le 15 Oct 2012
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.

Réponse acceptée

Matt Fig
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.
  2 commentaires
schwj1000
schwj1000 le 15 Oct 2012
Thanks Matt, I'm starting to get it now. But one thing I'm wondering is, say the user asks for three output arguments, and only 2 are required - is there a way to only return 2 outputs, if three were asked for?
For an example, this is from an old assignment. We had to create a program that does LU or LUP factorization. If no pivoting is neccessary, only the L and U matrices are needed as outputs (since the P would just be an identity matrix). Is there a way to accomplish this or no?
Either way, you've been a huge help. (the example program really helped) Thanks!
Matt Fig
Matt Fig le 16 Oct 2012
Modifié(e) : Matt Fig le 16 Oct 2012
If the user asks for three output arguments, the function must return three or it will error. However, you can set the third argument to [] if conditions warrant. Something like:
varargout(3:nargout) = {[]};

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by