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

8 vues (au cours des 30 derniers jours)
ELI
ELI le 23 Mar 2015
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?

Réponses (1)

Jos (10584)
Jos (10584) le 23 Mar 2015
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 commentaires
ELI
ELI le 23 Mar 2015
If I do that, I get error:
Subscripted assignment between dissimilar structures.
Jess
Jess le 7 Mar 2017
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by