变量似乎在每次循环迭代时改变大小

编程入门 行业动态 更新时间:2024-10-27 10:27:09
本文介绍了变量似乎在每次循环迭代时改变大小 - 什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

编写以下Matlab代码时:

When writing the following Matlab code:

for ii=1:n x(ii) = foo( ii ); % foo is some function of ii that cannot be vectorized. end

我得到以下 m-lint 警告:

变量 x 似乎在每次循环迭代时改变大小

The variable x appears to change size on every loop iteration

我的问题:

  • 该警告意味着什么?
  • 为什么每次迭代都会改变变量大小是件坏事?
  • 如何解决这个问题?
  • <这个问题与这个问题不重复,因为它涉及预分配的更一般方面,而不是它的特定实例。

    This question is not duplicate of this one, since it deals with more general aspects of preallocation, rather a specific instance of it.

    推荐答案

    嗯,首先要做的事情。

    这段代码在语法方面是正确的,它将正确执行返回预期结果: ii x 的元素将包含值 foo(ii)。 但是,在运行这一小段代码之前,未定义变量 x 。现在,当循环开始时, x(1)被赋值为 foo(1),因此Matlab创建 x 作为长度为1的数组。在第二次迭代 x(2)被分配值 foo(2),因此Matlab需要更改 x 的长度为2,依此类推: x 在每次迭代时更改其长度/大小。

    This code is correct in terms of syntax and it will execute correctly returning the expected result: the ii-th element of x will contain the value foo( ii ). However, before this small piece of code runs, the variable x is not defined. Now, when the loop starts, x(1) is assigned the value foo( 1 ), and so Matlab creates x as a length-1 array. At the second iteration x(2) is assigned the value foo( 2 ) and so Matlab needs to change x to be of length 2, and so on: x changes its length/size at each iteration.

    考虑当 x

    最简单的解决方案是预先分配所有空间 x 需要在循环之前:

    The simplest solution is to pre-allocate all the space x needs before the loop:

    x = zeros(1,n); for ii=1:n x( ii ) = foo( ii ); end

    通过预先分配,我们确定 x 预先分配了它需要的所有内存,因此在循环执行时不需要昂贵的内存分配/复制。

    By pre-allocating we ascertain that x is allocated all the memory it requires up-front, thus no costly memory allocation/copy is needed when the loop is executing.

    如果你太懒(和我一样)并且不想预先分配,你可以简单地说:

    If you are too lazy (like me) and don't want to pre-allocate you can simply:

    for ii=n:-1:1 x( ii ) = foo( ii ); end

    这样,第一次 x 被分配一个值,它被分配给它的 n -th元素(最后一个),因此Matlab 立即为所有人分配空间 n 元素 x 。 酷!

    This way, the first time x is assigned a value it is assigned to its n-th element (the last one) and therefore Matlab immediately allocates room for all n elements of x. Cool!

    更多推荐

    变量似乎在每次循环迭代时改变大小

    本文发布于:2023-11-30 18:05:48,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1651011.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:变量   大小   迭代

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!