本文介绍了在MATLAB中按std :: vector :: reserve(n)预先分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当您大致了解尺寸要求时,reserve非常有用.有谁知道在MATLAB中预分配数组的类似方法吗?

So reserve is quite useful when you have a rough idea of your size requirements. Does anyone know of a similar method to pre-allocate arrays in MATLAB?

我对下面的hacky(但有效)方法并不真正感兴趣:

I'm not really interested in hacky (but effective) methods like the following:

x = zeros(1000,1);
for i = 1:10000
    if i > numel(x)
       x = [x;zeros(size(x))];
    end
    x(i) = rand;
end
x(i+1:end) = [];

推荐答案

"hacky"方式是唯一的方法.但是,您不需要检查i< = numel(x).数组将自动展开(但不会将数组加倍):

The "hacky" way is the only way to do it. However, you do not need to check i <= numel(x). The array will be expanded automatically (but without array doubling):

x = zeros(1000,1);
for i = 1:10000
    x(i) = rand;
end
x(i+1:end) = [];

为简化操作,同时仍保留数组加倍,您可以编写一个类,或编写一些辅助函数(如下).

To keep it simple while still retaining the array doubling, you can write a class, or simply a few helper functions (below).

与手动hack相比,使用helper函数会减慢速度.在MATLAB 2010中,它仍然比幼稚的增长要快得多.在MATLAB 2011中,天真的方法实际上更快,这表明该版本的分配更智能.也许它足够快,所以根本不需要黑客.感谢安德鲁·扬克(Andrew Janke)指出了这一点.

The usage of helper functions will slow things down compared to the manual hack. In MATLAB 2010 it is still much faster than naive growth. In MATLAB 2011 the naive approach is actually faster, suggesting that this version has smarter allocation. Perhaps it is fast enough so that no hack is needed at all. Thanks to Andrew Janke for pointing this out.

function listtest()
    n = 10000;
    l = new_list();
    for i=1:n
        l = list_append(l, i);
    end
    a = list_to_array(l);
end

function l = new_list()
    l = [0 0];
end
function l = list_append(l, e)
    if l(1)+1 == length(l)
        l(length(l)*2) = 0;
    end
    l(1) = l(1)+1;
    l(l(1)+1) = e;
end
function a = list_to_array(l)
    a = l(2:1+l(1));
end

编辑(来自AndrewJanke)

EDIT (from AndrewJanke)

这里是比较实现速度的代码.

Here's code to compare the speed of the implementations.

function manual_reserve_example(n)
x = zeros(1000,1);
for i = 1:n
    if i > numel(x)
       x = [x;zeros(size(x))];
    end
    x(i) = i;
end
x(i+1:end) = [];
end

function naive_growth(n)
x = 0;
for i = 1:n
    x(i) = i;
end
end

function compare_them(n)
fprintf('Doing %d elements in Matlab R%s\n', n, version('-release'));
tic;
naive_growth(n);
fprintf('%30s  %.6f sec\n', 'naive_growth', toc);
tic;
manual_reserve_example(n);
fprintf('%30s  %.6f sec\n', 'manual_reserve', toc);
tic;
listtest(n);
fprintf('%30s  %.6f sec\n', 'listtest', toc);
end

这篇关于在MATLAB中按std :: vector :: reserve(n)预先分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:01