gpt4 book ai didi

arrays - Matlab 是否接受非整数索引?

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:19 24 4
gpt4 key购买 nike

当然不是! ...或者是吗?让我们做一些测试。

定义 x = [10 20 30 40 50]。然后,如预期的那样,以下任何语句都会在 Matlab 中给出错误(下标索引必须是实数正整数或逻辑数):

>> x(1.2)
>> x(-0.3)
>> x([1.4 2 3])
>> x([1.4 2.4 3.4])
>> x([1.4:4])
>> x(end/2)

但是,冒号索引 接受非整数值。以下所有工作在最近的 Matlab 版本中,尽管有警告(用作索引时冒号运算符需要整数操作数)。

>> x(1.2:3)
ans =
10 20

>> x(0.4:3)
ans =
10 10 20

>> x(0.6:3)
ans =
10 20 30

>> x(1.2:0.7:5)
ans =
10 20 30 30 40 50

>> x(-0.4:3)
ans =
10 10 20 30

如果冒号表达式包含 end,它也有效:

>> x(1.5:end-2)
ans =
20 30

>> x(1.5:end/6:end-1)
ans =
20 20 30 40

另一方面,下面的代码不起作用,并给出与上面相同的错误:

>> x(-0.6:2)
>> x(-0.5:2)

观察到的行为可以总结如下:

  • 当使用冒号索引 时,会出现一些内部舍入。冒号索引是 a:ba:b:c 形式的表达式。当索引数组是标准数组时,不会发生舍入,例如 [a b c] 甚至 [a:b][a:b:c]
  • 四舍五入到最接近的整数,但-0.50.5 之间的数字是特殊情况>:它们四舍五入为 1 而不是 0。当然,如果舍入后的整数为负数,则会发生错误。

Octave 的最新版本中可以看到类似的行为,除了:

  • 显然,正常四舍五入到最接近的整数,没有将 -0.50.5 之间的数字视为特殊情况;所以这些给出了一个错误:

    >> x(0.4:3)
    >> x(-0.4:3)
  • 当非整数范围包含单个值时会发出错误:x(2.4:4) 有效,但 x(3.4:4)不会(当然,x([2.4 3.4])x(3.4) 也不起作用)。

除此之外,结果与Matlab中相同,并发出警告(Non-integer range used as index)。

警告以及 Octave 与 Matlab 的工作方式类似的事实表明这是有意的行为。是否在某处记录?谁能提供更多信息或阐明这一点?

最佳答案

补充观察:

  • x(1.2:3) 理论上应解释为:subsref(x, substruct('()',1.2:3))。但是,如问题中所述,“当索引数组是标准数组时不进行舍入”,这会导致显式下标引用失败。这表明类似于 logical short-circuiting 的机制或者也许 multithreaded partitioning (中间变量“未真正创建”)发生。

  • 发出的警告的标识符是 MATLAB:colon:nonIntegerIndex

理论:

  • 也许存在下标引用的重载版本,其中有一个检测下标本身是否为整数的初始步骤。如果不是,MATLAB 会将其“重定向”到其他一些类系列 ( example )。

官方评论:

  • 这就是Steve Eddins of TMW不得不在这个问题上说:

    ... in its earliest days, MATLAB implementers had a tendency to be as permissive as possible with respect to input validation. Over time, we realized that this philosophy wasn’t always the best one for users, and we started making some of the language rules tighter and more regular. One example was the introduction of error messages about invalid indices (noninteger, nonpositive, etc.). However, we couldn’t always tighten up the behavior as much as we liked. Sometimes that was because we discovered that too much user code was exploiting the original behavior. That is one of the reasons you continue to see this kind of behavior variation in some places. ... I would advise users to only use integer-valued indices. Users can explicitly call round or floor or whatever to convert the output of the colon operator to be integer-valued.

关于arrays - Matlab 是否接受非整数索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com