The βnaturalβ solution is to initialize (create) each structure with a fixed field order . When the structure is created in this way, you can fill in its fields in any order.
Alternatively, you can encapsulate the creation into a function . This simplifies the code and ensures that the order is consistent. In your case, the creator function may be
create_student = @(x) struct('name',[], 'age',[]); %
So your code will become
students = create_student(); %// call struct creator students.name = 'John'; students.age = 28; student2 = create_student(); %// call struct creator student2.age = 23; student2.name = 'Steve'; students(2) = student2; %// Now this works
Luis mendo
source share