我想向一个结构体数组中添加数据,但所添加的结构体字段的顺序不一定与原始结构体的字段相同。
例如:
% Works fine:
students.name = 'John';
students.age = 28;
student2.name = 'Steve';
student2.age = 23;
students(2) = student2;
% Error if the order of the fields of student2 is reversed
students.name = 'John';
students.age = 28;
student2.age = 23;
student2.name = 'Steve';
students(2) = student2; % Error: Dissimilar structs
是否有一种结构体的变体可以在不必保持字段相同顺序的情况下添加数据?
编辑:一种解决方法是始终使用matlabs的“orderfields”,该函数按字母顺序排序字段。也就是说,上述错误的示例将变为:
% Order fields alphabetically
students.name = 'John';
students.age = 28;
student2.age = 23;
student2.name = 'Steve';
students = orderfields(students);
student2 = orderfields(student2);
students(2) = student2; % Works
我不确定这是否是最自然的解决方案。
orderfields
应用于这两个结构体可能会解决这个问题。 - Daniel