如何优雅地忽略 MATLAB 函数的某些返回值 [英] How to elegantly ignore some return values of a MATLAB function

查看:53
本文介绍了如何优雅地忽略 MATLAB 函数的某些返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从函数中获取第 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;

现在假设,我只对 第三 返回值感兴趣.这可以通过创建一个虚拟变量来实现:

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

(只是为了检查,我还验证了该技术适用于 [mu,mu,mu]=polyfit(x,y,n) 如果您关心的是 polyfit 是第三个参数.)

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆