Matlab 报错 Consider preallocating for speed

示例:

k=5;
a=zeros(k,k);
for m=1:k
    for n=1:k 
		a(m,n)=1/(m+n-1); 
    end
end
for i=1:1:10
    b(i)=i+20;
end


报错如下:


Explanation
The size of the indicated variable or array appears to be changing with each loop iteration. Commonly, this message appears because an array is growing by assignment or concatenation. Growing an array by assignment or concatenation can be expensive. For large arrays, MATLAB must allocate a new block of memory and copy the older array contents to the new array as it makes each assignment.
Programs that change the size of a variable in this way can spend most of their run time in this inefficient activity. There is also significant overhead in shrinking an array on each iteration or in changing the size of a variable on each iteration. In such cases, MATLAB must reallocate and copy the contents repeatedly.


解释:变量在每次循环时都会改变数组的大小,请考虑提前分配数组的大小以提高速度.

在MATLAB中,改变数组的大小是很耗时间的工作,所以就有了这样的警告。

解决办法:在代码开始时,对数组b做合理的初始化,例如:

b=zeros(1,10);为b赋值为1行10列的0矩阵.

或者

b=zeros(10,1);为b赋值为10行1列的0矩阵.

运行这样的代码就不会现警告.


k=5;  
a=zeros(k,k);  
b=zeros(1,10);
for m=1:k  
    for n=1:k   
        a(m,n)=1/(m+n-1);   
    end  
end  
for i=1:1:10  
    b(i)=i+20;  
end 


猜你喜欢

转载自blog.csdn.net/flywiththejet/article/details/72458092
今日推荐