Simple explanation - how to use varargout

조회 수: 50 (최근 30일)
schwj1000
schwj1000 2012년 10월 15일
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.

채택된 답변

Matt Fig
Matt Fig 2012년 10월 15일
편집: Matt Fig 2012년 10월 15일
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
schwj1000
schwj1000 2012년 10월 15일
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 2012년 10월 16일
편집: Matt Fig 2012년 10월 16일
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) = {[]};

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by