Array of the MATLAB class

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

Using the naive method gives absorptive 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.  

Inheritance of the handle significantly improves 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 acceptable performance, especially given the increase in redistribution costs

Is there a way to reassign an array of classes? Any ideas on how to effectively manage the number of objects?

Thanks
Dani

+3
source share
3 answers

This solution extends to Marc 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:

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

, ?

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.
+5

repmat - :

b = repmat(Request, 1000, 1);

Elapsed time is 0.056720 seconds


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

, mlint .

+2

Source: https://habr.com/ru/post/1699334/


All Articles