Structure initialization with repmat

前端 未结 2 548
天命终不由人
天命终不由人 2021-01-26 07:03

I want to initalize structures and it seems to be too slow. How do I do it with repmat, which is supposed to be a much faster solution in Matla

2条回答
  •  逝去的感伤
    2021-01-26 07:45

    Here's the equivalent vectorized code of the first code snippet:

    myloc.one = struct('id', zeros(30, 5), ...
      'matrixBig', struct('matrixBig', repmat({zeros(6)}, 30, 1)), ...
      'final', struct('final', repmat({zeros(30, 1)}, 5, 10)));
    

    or alternatively:

    myloc.one = struct('id', zeros(30, 5), ...
       'matrixBig', repmat(struct('matrixBig', zeros(6)), 30, 1), ...
       'final', repmat(struct('final', zeros(30, 1)), 5, 10));
    

    Choose the one you like most.

    As for the second (edited) part, it can be replaced with:

    myObject = repmat({struct('s', zeros(6, 1), 'f', zeros(6, 1))}, 30, 10);
    

    Note that there is no need to preallocate anything because there aren't any explicit loops here.

提交回复
热议问题