Matlab中没有越界

发布于 2024-10-20 19:45:58 字数 369 浏览 1 评论 0原文

我在 Matlab 中注意到以下内容。

>> a = [1, 3];
>> a(3, 4) = 1
a =

 1     2     0     0
 0     0     0     0
 0     0     0     1
>> a(5, 4)
??? Attempted to access a(5,4); index out of bounds because size(a)=[3,4].

a 最初的大小不是 1 x 2 吗?为什么当我写入 a(3, 4) 时它不会抱怨越界,而只有当我读取 a(5, 4) 时才抱怨越界?

I notice the following in Matlab.

>> a = [1, 3];
>> a(3, 4) = 1
a =

 1     2     0     0
 0     0     0     0
 0     0     0     1
>> a(5, 4)
??? Attempted to access a(5,4); index out of bounds because size(a)=[3,4].

Isn't a of size 1 by 2 initially? Why wouldn't it complain out of bound when I write to a(3, 4) but only when I read a(5, 4)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静赏你的温柔 2024-10-27 19:45:58

当您写入数组中以前不存在的元素时,数组将增加到新的大小,并在数字数组的情况下用零填充,或者用单元格或结构体等空元素填充。这样做是为了您的方便,因为自己增加数组需要大量输入。请注意,对于实际代码,您可能经常希望避免像这样更改数组大小,因为它可能会降低可读性,并且如果您在具有多次迭代的循环内增加这样的数组,它会显着影响性能。因此,通常最好将数组预先指定为正确的大小(这具有让您可以控制填充值的额外好处)。

当你想读取一个不存在的元素时,就没有什么可以读取的了。可以想象,Matlab 可能会返回 0 或 NaN,但故意发生越界读取的情况比写入的可能性要小得多,因此 Matlab 会抛出错误。

When you write to a previously non-existing element in an array, the array is augmented to the new size, and padded with zeros in case of a numeric array, or empty elements with e.g. cells or structs. This is done for your convenience, since augmenting the array by yourself requires a lot of typing. Note that for actual code, you may often want to avoid changing array size like this, since it may decrease readability, and it can noticeably affect performance if you grow an array like this inside a loop with many iterations. Thus, it is generally better to pre-assign your arrays to the correct size (which has the added benefit of giving you control over the padding value).

When you want to read a non-existing element, there is nothing that can be read. Conceivably, Matlab could return 0 or NaN, but reading outside the bounds is much less likely to happen on purpose than writing, so Matlab throws an error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文