views:

1152

answers:

3
+2  Q: 

MATLAB class array

What would be the best way to manage large number of instances of the same class in MATLAB?

Using the naive way produces absymal results:

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.

Inheriting handle drastically improve the results:

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.

but still not an acceptable performance, especially considering the increasing reallocation overhead

Is there a way to preallocate class array? Any ideas on how to manage lange quantities of object effectively?

Thanks,
Dani

+2  A: 

repmat is your friend:

b = repmat(Request, 1000, 1);

Elapsed time is 0.056720 seconds


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

Growing by appending is abysmally slow, which is why mlint calls it out.

Marc
The problem: b = repmat(RequestH, 1000, 1);b(1).num=99;b(2).numans = 99
Dani
That's the nature of a handle class. It's fundamentally a singleton class, so all "instances" actually point to a single instance. I was just showing the speedup. Weather to use a Handle class or not is a very separate question.
Marc
+2  A: 

This solution expands on Marc's answer. Use repmat to initialize an array of RequestH objects and then use a loop to create the desired objects:

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

This is an improvement over:

>> a=[];tic,for i=1:10000 a=[a RequestH];end;toc
Elapsed time is 2.313368 seconds.
b3
+2  A: 

Coming to this late, but would this not be another solution?

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

Or even better:

a(1000, 1) = Request;
Elapsed time is 0.019755 seconds.
jjkparker