selection of the right VARARGOUT
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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.
0 个评论
更多回答(2 个)
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');
0 个评论
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
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 Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!