Efficient Array Preallocation in MATLAB

后端 未结 2 697
情话喂你
情话喂你 2021-02-20 02:44

One of the first things one learns about programming efficiently in MATLAB is to avoid dynamically resizing arrays. The standard example is as follows.

N = 1000;         


        
2条回答
  •  遥遥无期
    2021-02-20 02:47

    How about letting Matlab take care of the allocation for you?

    clear a;
    for i=N:-1:1
        a(i) = cos(i);
    end
    

    Then Matlab can allocate and fill the array with whatever it thinks will be optimal (probably zero). You don't have the debugging advantage of NaNs, though.

提交回复
热议问题