How do I insert a substructure within an existing structure at a specific index

6 次查看(过去 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?

采纳的回答

Stephen23
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:
  • STRUCT2CELL, insert, CELL2STRUCT.
  • ORDERFIELDS:
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'})
existingStruct = struct with fields:
a: [1×1 struct] b: [1×1 struct] new: [1×1 struct] c: [1×1 struct] d: [1×1 struct]
You can use FIELDNAMES() to get a cell array of the fieldnames.
  2 个评论
deathtime
deathtime 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".
Stephen23
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'})
existingStruct = struct with fields:
a: [1×1 struct] b: [1×1 struct] new: [1×1 struct] c: [1×1 struct] d: [1×1 struct]

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by