- STRUCT2CELL, insert, CELL2STRUCT.
- ORDERFIELDS:
How do I insert a substructure within an existing structure at a specific index
7 次查看(过去 30 天)
显示 更早的评论
Let's say I have an existing structure:
existingStruct.a.val1 = 1;
existingStruct.a.val2 = 2;
existingStruct.b.val1 = 3;
existingStruct.b.val2 = 4;
existingStruct.c.val1 = 5;
existingStruct.c.val2 = 6;
existingStruct.d.val1 = 7;
existingStruct.d.val2 = 8;
Now I have a substructure:
new.val1 = 9;
new.val2 = 10;
I want to place this substructure within b and c in the existing sturcure. So the new structure looks like this:
existingStruct.a.val1 = 1;
existingStruct.a.val2 = 2;
existingStruct.b.val1 = 3;
existingStruct.b.val2 = 4;
existingStruct.new.val1 = 9;
existingStruct.new.val2 = 10;
existingStruct.c.val1 = 5;
existingStruct.c.val2 = 6;
existingStruct.d.val1 = 7;
existingStruct.d.val2 = 8;
What is the simplest way to do this?
0 个评论
采纳的回答
Stephen23
2024-3-4
编辑:Stephen23
2024-3-4
"What is the simplest way to do this?"
With a structure array this would be easy with some indexing. It would also make accessing the data easier.
But because you are using a scalar structure with lots of fields (and most likely forced meta-data into the fieldnames) you will have to do this a longer way e.g. one of these:
existingStruct.a.val1 = 1;
existingStruct.a.val2 = 2;
existingStruct.b.val1 = 3;
existingStruct.b.val2 = 4;
existingStruct.c.val1 = 5;
existingStruct.c.val2 = 6;
existingStruct.d.val1 = 7;
existingStruct.d.val2 = 8;
new.val1 = 9;
new.val2 = 10;
existingStruct.new = new;
existingStruct = orderfields(existingStruct,{'a','b','new','c','d'})
You can use FIELDNAMES() to get a cell array of the fieldnames.
2 个评论
Stephen23
2024-3-4
编辑:Stephen23
2024-3-4
"What if I wanted to duplicate the field "b" in the existing structure - just call the duplicated field "new", and have it in the position as before, between "b" and "c"."
existingStruct.a.val1 = 1;
existingStruct.a.val2 = 2;
existingStruct.b.val1 = 3;
existingStruct.b.val2 = 4;
existingStruct.c.val1 = 5;
existingStruct.c.val2 = 6;
existingStruct.d.val1 = 7;
existingStruct.d.val2 = 8;
existingStruct.new = existingStruct.b;
existingStruct = orderfields(existingStruct,{'a','b','new','c','d'})
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!