如何优雅地忽略MATLAB函数的某些返回值 [英] How to elegantly ignore some return values of a MATLAB function
问题描述
是否可以从函数中获取第n个"返回值,而不必在此之前为所有 n-1
个返回值创建伪变量?
Is it possible to get the 'nth' return value from a function without having to create dummy variables for all n-1
return values before it?
比方说,我在MATLAB中具有以下功能:
Let's say, I have the following function in MATLAB:
function [a,b,c,d] = func()
a = 1;
b = 2;
c = 3;
d = 4;
现在假设,我只对 third 返回值感兴趣.这可以通过创建一个虚拟变量来实现:
Now suppose, I'm only interested in the third return value. This can be accomplished by creating one dummy variable:
[dummy, dummy, variableThatIWillUse, dummy] = func;
clear dummy;
但是我认为这有点丑.我认为您也许可以执行以下操作之一,但不能:
But I think this is kind of ugly. I would think that you might be able to do something like one of the following things, but you can't:
[_,_,variableThatIWillUse,_] = func;
[,,variableThatIWillUse,] = func;
variableThatIWillUse = func(3);
variableThatIWillUse = func()(3);
有什么优雅方法可以做到这一点吗?
Are there any elegant ways to do this that do work?
到目前为止,最好的解决方案是简单地将 variableThatIWillUse
用作虚拟变量.这使我不必创建一个真正的伪变量,该变量会污染工作空间(或者我需要清除).简而言之:解决方案是对每个返回值使用 variableThatIWillUse
,直到有趣的返回值为止.之后的返回值可以简单地忽略:
So far, the best solution is to simply use the variableThatIWillUse
as a dummy variable. This saves me from having to create a real dummy variable that pollutes the work-space (or that I would need to clear). In short: the solution is to use the variableThatIWillUse
for every return value up until the interesting one. Return values after can simply be ignored:
[variableThatIWillUse, variableThatIWillUse, variableThatIWillUse] = func;
我仍然认为这是非常丑陋的代码.
I still think this is very ugly code.
推荐答案
这有点像骇客,但是可以用:
This is somewhat of a hack, but it works:
首先是一个简单的示例函数:
First a quick example function:
Func3 = @() deal(1,2,3);
[a,b,c]=Func3();
% yields a=1, b=2, c=3
现在的关键是,如果您在多表达式分配的左侧使用变量两次,则较早的分配会被较晚的分配所破坏:
Now the key here is that if you use a variable twice on the left-hand side of a multiple-expression assignment, an earlier assignment is clobbered by the later assignment:
[b,b,c]=Func3();
% yields b=2, c=3
[c,c,c]=Func3();
% yields c=3
(只需检查一下,我还验证了此技术是否适用于 polyfit(x,y,n)
[mu,mu,mu = polyfit(x,y,n)),/code>是第三个参数.)
(Just to check, I also verified that this technique works with [mu,mu,mu]=polyfit(x,y,n)
if all you care about from polyfit
is the third argument.)
有更好的方法;请参阅 ManWithSleeve的答案.
There's a better approach; see ManWithSleeve's answer instead.
这篇关于如何优雅地忽略MATLAB函数的某些返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!