Matlab预分配与无分配,第二种比较快,为什么? [英] Matlab Pre-allocation vs. no allocation, the second one is faster, why?

查看:121
本文介绍了Matlab预分配与无分配,第二种比较快,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约三个月前,我在Matlab上运行了一个样本,发生了一些奇怪的事情.今天,当我测试其他问题的答案时(如何我可以对再次发生的单元格的元素进行排序吗?).它与Matlab中的预分配有关.让我解释一下:

About three month ago, I was running a sample in Matlab and something strange happened. Today, while I was testing the answers to my other question (How can I sort the elements of a cell?) that happened again. It is about pre-allocation in Matlab. Let me explain it:

考虑此测试代码,我们尝试通过以下三种方法创建矩阵(ones(100,100)):

Consider this test code in which we try to create a matrices (ones(100,100)) in three ways:

  1. 没有预分配(声明I=[])
  2. 具有预分配(声明I=zeros(100,100))
  3. 完全没有分配(我什么也没声明)
  1. No pre-allocating (declaring I=[])
  2. With pre-allocation (declaring I=zeros(100,100))
  3. No allocation at all (I declare nothing)

代码:

N=1000;
sum0=0;sum1=0;sum2=0;
for q=1:N

    % No pre-allocating
    tic
    I=[];
    for i=1:100
        for j=1:100
            I(i,j)=1;
        end
    end
    a=toc;sum0=sum0+a;

    % with pre-allocation
    tic
    I=zeros(100,100);
    for i=1:100
        for j=1:100
            I(i,j)=1;
        end
    end
    a=toc;sum1=sum1+a;

    % if nothing is declared, I call it no-allocation
    tic
    for i=1:100
        for j=1:100
            I(i,j)=1;
        end
    end
    a=toc;sum2=sum2+a;
end

结果是:

sum0 =1.53790886830589    //no pre-allocation
sum1 = 0.127538555877912  //with pre-allocation
sum2 = 0.120887850271473  //no allocation

第三种方法(我不写I=[]I=zeros(100,100)的方法)是最好的方法!这也发生在我之前的问题中. (请参阅更新部分)

The third method (where I do not write I=[] or I=zeros(100,100)) is the best approach! This happened in my previous question too. (see the update part)

此方法与第一种和第二种方法有什么区别?

推荐答案

第三次运行循环时,I已存在于工作空间中.因此,该循环与第二个循环一样快,只是您不再调用zeros.

The third time you run the loop, I already exists in the workspace. Thus, the loop is as fast as the second one, except that you're not calling zeros anymore.

我建议第二次和第三次用JK替换I,以避免在计算计时时出错(或在每次循环前调用clear I;感谢@EitanT).

I suggest replacing I with J and K the second and third time to avoid errors when calculating timings (or call clear I before each loop; thanks @EitanT).

编辑或者,您可以使用隐式预分配,在其中向后循环,以便您分配的第一个元素定义整个数组:

EDIT As an alternative, you can use implicit preallocation, where you loop backwards, so that the first element you assign defines the entire array:

for i=100:-1:1
    for j=100:-1:1
       I(i,j) = 1;
    end
end

这篇关于Matlab预分配与无分配,第二种比较快,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆