3

在 MATLAB 中管理大量同一类的实例的最佳方法是什么?

使用幼稚的方式会产生极端的结果:

classdef Request
    properties
        num=7;
    end
    methods
        function f=foo(this)
            f = this.num + 4;
        end
    end
end

>> a=[];  

>> tic,for i=1:1000 a=[a Request];end;toc  

Elapsed time is 5.426852 seconds.  

>> tic,for i=1:1000 a=[a Request];end;toc  
Elapsed time is 31.261500 seconds.  

继承句柄极大地改善了结果:

classdef RequestH < handle
    properties
        num=7;
    end
    methods
        function f=foo(this)
            f = this.num + 4;
        end
    end
end

>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.174573 seconds.

但仍然不是可接受的性能,特别是考虑到重新分配开销的增加

有没有办法预先分配类数组?关于如何有效管理对象数量的任何想法?

谢谢,
丹妮

4

3 回答 3

5

这么晚了,但这不是另一种解决方案吗?

a = Request.empty(1000,0); tic; for i=1:1000, a(i)=Request; end; toc;
Elapsed time is 0.087539 seconds.

甚至更好:

a(1000, 1) = Request;
Elapsed time is 0.019755 seconds.
于 2010-03-10T14:48:33.053 回答
4

此解决方案扩展了Marc 的答案。使用repmat初始化 RequestH 对象数组,然后使用循环创建所需的对象:

>> a = repmat(RequestH,10000,1);tic,for i=1:10000 a(i)=RequestH;end;toc
Elapsed time is 0.396645 seconds.

这是对以下方面的改进:

>> a=[];tic,for i=1:10000 a=[a RequestH];end;toc
Elapsed time is 2.313368 seconds.
于 2008-11-12T21:11:05.053 回答
2

repmat是你的朋友:

b = repmat(Request, 1000, 1);

Elapsed time is 0.056720 seconds


b = repmat(RequestH, 1000, 1);
Elapsed time is 0.021749 seconds.

通过追加增长非常缓慢,这就是为什么 mlint 将其称为。

于 2008-11-09T21:49:46.617 回答