0

I am trying to preallocate an array of structures but without knowing which fields are contained in the structure. Is there a way to preallocate a 1x4 struct without knowing how much fields it will contain ?

Following many previous questions here and here the way to preallocate an array of structure, knowing the fields would be :


N = 10;
struct_array = struct('x',cell(1,N),'y',cell(1,N));

for i = 1:N
    a.x = i*i;
    a.y = num2str(i+i);
    struct_array(i) = a;
end
Arthur
  • 508
  • 2
  • 14
  • 1
    Are you trying to preallocate this array because the editor tells you to 'consider preallocating for speed'? If so, don't bother unless profiling actually shows you it's too slow. – nekomatic Jul 12 '19 at 09:02
  • 1
    You can create an array of blank structs then populate the fields in each struct accordingly. The example you provided is not a correctly working one. Can you show us an actual example of what you want to achieve? – rayryeng Jul 12 '19 at 09:04
  • @nekomatic Yes I am. Actually by profiling this example preallocating is slower than using the for loop without preallocating. Have you an idea about this behavior ? – Arthur Jul 12 '19 at 09:06
  • @rayryeng the example is pretty close to what I'm trying to do, the only significant difference in my real code is that a is given as an output of a function. – Arthur Jul 12 '19 at 09:08
  • If you don't know the outputs, there's likely something a bit janky about the structure of your code. The difficulty in pre-allocation here is an indication that you could be more considerate about how you're handling your data. i.e. if *you* don't know what outputs to expect, how can you expect *MATLAB* to know what outputs to expect? – Wolfie Jul 12 '19 at 10:19
  • Let me rephrase what I mean : I don't want to hardcode the name of the fields in case I choose to change the output of my function a some point. That is why I try to avoid a specific declaration as seen in line 2 of the code given in the question. Does that make more sense ? Note that my structure is known and the number of fields is constant. – Arthur Jul 12 '19 at 10:25

0 Answers0