Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 875
Dani Avatar asked Jun 26 '26 16:06

Dani


2 Answers

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.
like image 56
jjkparker Avatar answered Jun 28 '26 12:06

jjkparker


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.
like image 27
b3. Avatar answered Jun 28 '26 12:06

b3.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!