gpt4 book ai didi

matlab - 是否有不强制字段顺序的 Matlab 结构变体?

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:44 25 4
gpt4 key购买 nike

我想将数据添加到结构数组,而添加的结构的字段不一定与原始结构的字段具有相同的顺序。例如:

% 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

我不确定这是否是最自然的解决方案。

最佳答案

“自然”的解决方案是用固定的字段顺序初始化(创建)每个结构。以这种方式创建结构后,您可以按任何顺序填充其字段。

此外,您可以将创建封装在一个函数中。这简化了代码并确保顺序一致。在您的情况下,创建者功能可能是

create_student = @(x) struct('name',[], 'age',[]); %// empty fields. Fixed order 

所以你的代码会变成

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

关于matlab - 是否有不强制字段顺序的 Matlab 结构变体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com