필터 지우기
필터 지우기

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

조회 수: 11 (최근 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