selection of the right VARARGOUT
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Fangjun Jiang
le 21 Oct 2011
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 commentaires
Plus de réponses (2)
Walter Roberson
le 21 Oct 2011
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 commentaires
Matthias Schabel
le 2 Oct 2016
Modifié(e) : Matthias Schabel
le 2 Oct 2016
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 commentaire
Walter Roberson
le 2 Oct 2016
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.)
Voir également
Catégories
En savoir plus sur Argument Definitions 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!