How do I copy fields name and their contents to another struct variable?

조회 수: 4 (최근 30일)
ELI
ELI 2015년 3월 23일
편집: Walter Roberson 2017년 3월 7일
Lets say that I have this code:
a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';
a(2).a='a1';
a(2).b='b1';
a(2).c='c1';
a(3).a='a1';
a(3).b='b1';
a(3).c='c1';
Now, I want to copy only a(2) to b(1) with its all fields. for example:
b=struct;
b(1)=a(2);
b(2)=a(3);
How can I do that?

답변 (1개)

Jos (10584)
Jos (10584) 2015년 3월 23일
a(1).x = 1
a(2).x = 2
a(3).x = 3
b(1:2) = a(2:3) % Is this what you want? b(1) now equals a(2) ...
  댓글 수: 2
ELI
ELI 2015년 3월 23일
If I do that, I get error:
Subscripted assignment between dissimilar structures.
Jess
Jess 2017년 3월 7일
What version of MATLAB are you using? The following works for me in 8.4.0.150421 (R2014b):
a=struct;
a(1).a='a1';
a(1).b='b1';
a(1).c='c1';
a(2).a='a2';
a(2).b='b2';
a(2).c='c2';
a(3).a='a3';
a(3).b='b3';
a(3).c='c3';
b(1:2) = a(2:3)
(Note that I changed the values slightly.)
Perhaps instead of
a(1).x = 1
a(2).x = 2
a(3).x = 3
you should write out x:
a(1).a = 1
a(2).a = 2
a(3).a = 3
It sounds like you're storing one thing in another wrong.

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by