selection of the right VARARGOUT

조회 수: 3 (최근 30일)
Meh
Meh 2011년 10월 21일
댓글: Walter Roberson 2016년 10월 2일
Hi, Let's say I have a function called FUN with 4 outputs a,b,c,d, as shown below
[a,b,c,d]=FUN(x)
Then I want to get an answer depending on which output I want, for example, if I enter:
[c]=FUN(x)
I want to get the desired output, NOT just the one on the first column (i.e value of a instead of c).
Thanx

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 10월 21일
In the new version of MATLAB, you can do [~,~,c]=FUN(x). See this blog http://blogs.mathworks.com/loren/2009/09/11/matlab-release-2009b-best-new-feature-or/
In old version, you have to do [trash, dummy,c]=FUN(x) and then clear trash and dummy.
Whether it allows you to have three outputs rather than the full four outputs will depend on how FUN(x) is written.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2011년 10월 21일
There is, by the way, no (supported) mechanism for a function to find out the name that an output variable is being assigned to.
Even if there were, the name could be rather messy to represent, seeing as it might be coded as (for example)
[R{aFunctionThatReturnsALogicalIndex()}] = YourFunction()
If you want to be able to be selective about outputs in this way, you could pass the output choice as an input to the function.
foo = YourFunction(X,'std');
foo2 = YourFunction(X,'mean');

Matthias Schabel
Matthias Schabel 2016년 10월 2일
편집: Matthias Schabel 2016년 10월 2일
Is there a way to capture the tilde output arguments within a function? For example, I have a function that computes two quantities, one expensive and one cheap :
function [expensive,cheap] = foo(in)
...
end
I usually want to do this :
ex = foo(in);
but sometimes I want to do this instead :
[~,ch] = foo(in);
Computation of expensive involves computation of cheap. Is there a way to capture the tilde and not bother to compute expensive when it isn't wanted?
function varargout = foo(in)
varargout{2} = computeCheap();
if (isempty(varargout{1}))
return;
else
varargout{1} = computeExpensive();
return;
end
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2016년 10월 2일
The easiest way to do that is to make the expensive one the second output, after which you can check nargout . If the user did not specify multiple outputs then nargout will be either 0 or 1 (depending on context.)

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by