Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array of structs in MATLAB?

Tags:

matlab

How can I preallocate an array of structs in MATLAB? I want to preallocate "a" in this example so that it does not resize several times.

a = [] for i = 1:100   a(i).x = i; end 
like image 705
Mohammad Moghimi Avatar asked Dec 01 '12 21:12

Mohammad Moghimi


People also ask

How do you declare an array of structs in MATLAB?

To create an array of structures using the struct function, specify the field value arguments as cell arrays. Each cell array element is the value of the field in the corresponding structure array element. For code generation, corresponding fields in the structures must have the same type.

How do you create an empty array of structs in MATLAB?

array = struct. empty(n,0);


2 Answers

Using repmat is by far the most efficient way to preallocate structs :

N = 10000;     b = repmat(struct('x',1), N, 1 ); 

This is ~10x faster using Matlab 2011a than preallocating via indexing, as in

N      = 10000; b(N).x = 1 

The indexing method is only marginally faster than not preallocating.

No preallocation:            0.075524     Preallocate Using indexing:  0.063774 Preallocate with repmat:     0.005234 


Code below in case you want to verify.

        clear;         N = 10000;      %1) GROWING A STRUCT         tic;         for ii=1:N             a(ii).x(1)=1;             end         noPreAll = toc;              %2)PREALLOCATING A STRUCT         tic;         b = repmat( struct( 'x', 1 ), N, 1 );         for ii=1:N             b(ii).x(1)=1;             end;           repmatBased=toc;              %3)Index to preallocate         tic;         c(N).x = 1;         for ii=1:N             c(ii).x(1)=1;             end;           preIndex=toc;          disp(['No preallocation:        ' num2str(noPreAll)])                     disp(['Preallocate Indexing:    ' num2str(preIndex)])         disp(['Preallocate with repmat: ' num2str(repmatBased)]) 

Results in command window:

No preallocation:        0.075524     Preallocate Indexing:    0.063774 Preallocate with repmat: 0.0052338 >>  

P.S. I'd be interested to know why this is true, if anyone can explain it.

like image 92
jerad Avatar answered Sep 21 '22 15:09

jerad


There's a nice discussion about this in Loren on the Art of MATLAB blog.

If I understand you correctly, here's a ways to initialize the struct you want:

a(100).x = 100; 

With this method, we can see that elements are filled in with empty arrays.

like image 20
bla Avatar answered Sep 19 '22 15:09

bla