Octave/MATLAB中Deal()函数的作用是什么? [英] What is the point of the deal() function in Octave / MATLAB?

查看:319
本文介绍了Octave/MATLAB中Deal()函数的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些参考代码像

那样简单地使用功能deal()

[a, b, c] = deal (1,2,3)

如文档所述(用于Octave )中,该函数将输入简单地复制到输出中. 在这种情况下,甚至在一般情况下,为什么使用deal()??我正在尝试学习更正确的" MATLAB/Octave用法,并且想知道是否遗漏了一些重要内容.也许是这种用法...

As described in the documentation (for Octave and for MATLAB), the function simply copies the inputs to the outputs. Why use deal() in this case, or even in general? I'm trying to learn "more correct" MATLAB/Octave usage, and wondering if I'm missing something significant. Perhaps, is this usage...

  • 传统上是风格上的或惯用的,而不是像a=1, b=2, c=3这样的简单分配,或者是像[a,b,c] = {1,2,3}{:}这样更难以理解的单元格列表拆包,但是比Python 这个问题?
  • 对于某些更优雅的功能很有用-例如,深层"与浅层"副本,如果deal()与复杂/可变参数一起使用,是否还存在这样的概念?
  • conventionally stylistic or idiomatic, in place of simple assignment like a=1, b=2, c=3 or the more arcane list-unpacking of cell-arrays like [a,b,c] = {1,2,3}{:}, but even more restricted than Python argument unpacking, like in this question?
  • useful for some more elegant feature -- e.g., "deep" versus "shallow" copy, if such a concept even exists here, if deal() were used with complicated/variable arguments?

我也理解单参数[a,b,c]=deal(42),但这本质上是a=b=c=42,并且[a,b,c]=deal(x)x分配给所有,而不是每个x的元素.

I also understand single-argument [a,b,c]=deal(42) but that's essentially a=b=c=42, and [a,b,c]=deal(x) assigns x to all, not elements-of-x to each.

或者也许只是我对这种琐碎的功能使用了过多的思考.

Or perhaps it's ONLY that I'm over-thinking this trivial use of the function.

推荐答案

我偶尔使用deal的一种非常有用的方法是创建返回多个输出参数的匿名函数.例如,

One really useful way that I occasionally use deal is to create anonymous functions that return multiple output arguments. For example,

>> f = @(x) deal(x^2,x^3);
>> [a,b] = f(3)
a =
     9
b =
    27

编辑,因为人们似乎发现这种模式可能有用,所以请注意一个怪癖,因为您必须返回全部输出.特别是,您不能使用a = f(3),否则会出错.要仅检索单个输出,请使用[a,~] = f(3)[~,b] = f(3).用于抑制输出参数的~语法大约在R2007a左右就出现了(恐怕我记不清确切的时间了)-在较旧的版本中,您将需要始终返回两个输出.希望对您有用.

Edit since people seem to find this pattern potentially useful, do note a quirk, in that you must return the full number of outputs. In particular, you can't use a = f(3), or it will error. To retrieve just a single output, use [a,~] = f(3) or [~,b] = f(3). The ~ syntax for suppressing output arguments has been around since about R2007a or so (I'm afraid I can't recall exactly when) - in older versions, you will need to always return both outputs. Hope that may be useful for you.

这篇关于Octave/MATLAB中Deal()函数的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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