什么是替代在MATLAB preallocating阵列? [英] What is the alternative to preallocating arrays in MATLAB?

查看:109
本文介绍了什么是替代在MATLAB preallocating阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  在MATLAB 数据可增长结构


因此​​,在我目前的MATLAB脚本,我有一个非常大的不确定的尺寸不断增长的阵列。目前什么我可以做这件事,因为如果我真的preallocate,它会采取很多很多很多倍的内存比它应该需要(值的最大可能数量为640每像素,但通常它是沿东西线2-5)。

通常在这种情况下,我会用在C ++载体或东西,它所生长指数相对于给定的容量。但我认为,在Matlab矩阵开始分裂不是目的驱动的C ++载体快得多。

你们有什么想对这样的事情最好的选择?或者我应该坚持正常的阵列和希望加入100k左右顺序的元素将工作?

先谢谢了。


解决方案

您可以尝试什么的std ::矢量元素再分配什么时候---一倍的容量,每次它填补了其具有的摊余成本计量的 O(1)

测试:

 功能test_MAT_vector    LIM = 5E4;
    %%#正常
    抽动;
    A =零(1,1);
    对于i = 1:LIM
        A(结束+ 1)= I;
    结束
    TOC    %%#的std ::载体克隆
    抽动;
    B =零(1,1);
    对于i = 1:LIM
        如果(ⅰ> numel(B))
            B = [B;零(numel(B)中,1)];
        结束
        B(1)= I;
    结束
    TOC结束

输出:


  

经过时间3.489820秒。


  
  

经过时间0.006710秒。


使用细胞

  %%#电池
抽动;
A =细胞(1,1);
对于i = 1:LIM
    A(结束+ 1)= {I};
结束
TOC


  

经过时间2.740792秒。


Possible Duplicate:
Growable data structure in MATLAB

So in my current MATLAB script, I have a very large indeterminate-sized growing array. There is currently nothing I can do about it, because if I actually preallocate, it would take many many many times more memory than it should need (maximum possible amount of values is 640 per pixel, but usually it's something along the lines of 2-5).

Usually in this case, I'd be using a vector in C++ or something, where it grows exponentially in relation to a given capacity. But I think the matrices in Matlab starts fragmenting much faster than the purpose driven C++ vectors.

What do you guys think is the best alternative to something like this? Or should I just stick with normal arrays and hope that adding around 100k elements sequentially will work?

Thanks in advance.

解决方案

You could try what std::vector does when reallocating elements --- double its capacity every time it fills up which has an amortized cost of O(1).

Test:

function test_MAT_vector

    LIM = 5e4;
    %%# Normal
    tic;
    A = zeros(1,1);
    for i = 1:LIM
        A(end+1) = i;
    end
    toc

    %%# std::vector clone
    tic;
    B = zeros(1,1);
    for i = 1:LIM
        if(i > numel(B))
            B = [B;zeros(numel(B),1)];
        end
        B(i) = i;
    end
    toc

end

Output:

Elapsed time is 3.489820 seconds.

Elapsed time is 0.006710 seconds.

Using cell

%%# cell
tic;
A = cell(1,1);
for i = 1:LIM
    A(end+1) = {i};
end
toc

Elapsed time is 2.740792 seconds.

这篇关于什么是替代在MATLAB preallocating阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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