How to initialize an array of structs in MATLAB?

前端 未结 6 476
暗喜
暗喜 2020-11-30 23:01

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:1         


        
6条回答
  •  余生分开走
    2020-11-30 23:27

    The way this is supposed to be done, and the simplest is

    a=struct('x',cell(1,N));
    

    If you fix the missing "tic" and add this method to the benchmarking code presented by jerad, the method I propose above is a bit slower than repmat but much simpler to implement, here is the output:

    No preallocation:        0.10137
    Preallocate Indexing:    0.07615
    Preallocate with repmat: 0.01458
    Preallocate with struct: 0.07588
    

    The reason that repmat is faster is because a value to each 'x' field is assigned during the pre-allocation, instead of leaving it empty. If the above pre-allocation technique is changed so we start with all the x fields with a value (one) assigned, like this:

        a=cell(1,N);
        a(:)={1};
        d=struct('x',a);
    

    Then, the benchmarking improves a lot, been very close or some time faster than repmat. The difference is so small that every time I run it it changes which one is faster. Here an output example:

    No preallocation:        0.0962
    Preallocate Indexing:    0.0745
    Preallocate with repmat: 0.0259
    Preallocate with struct: 0.0184
    

    Conversely, if the repmat pre-allocation is changed to set the field empty, like this

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

    All the speed advantage is lost

提交回复
热议问题