编写以下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 c
最简单的解决方案是预先分配所有空间 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!
更多推荐
变量似乎在每次循环迭代时改变大小
发布评论