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

6 views (last 30 days)
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?

Accepted Answer

Stephen23
Stephen23 on 4 Mar 2024
Edited: Stephen23 on 4 Mar 2024
"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 Comments
deathtime
deathtime on 4 Mar 2024
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 on 4 Mar 2024
Edited: Stephen23 on 4 Mar 2024
"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]

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!