Copying structure to structure
79 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kristoffer Clasén
el 9 de Nov. de 2020
Comentada: Kristoffer Clasén
el 30 de Nov. de 2020
I'm trying to copy structure fields from one struct to a new struct as:
W; %Is a struct with fields i.e. W.case(1).data1; W.case(2).data1..... etc.
d(10) = struct(); %Initializing the struct
for i1 = 1:10
d(i1) = W.field(i1)
end
But this doesn't work because "Subscripted assignment between dissimilar structures". Indexing struct "d" like this never work. So, what do I do? I can copy field by field but that seems rather tedious.
0 comentarios
Respuesta aceptada
Walter Roberson
el 9 de Nov. de 2020
d = struct('data1', {W.case.data1});
This would make d into a struct array with a field named 'data1' that held the case(:).data1 values.
If you have multiple fields then you can, for example,
d = struct('data1', {W.case.data1}, 'data2', {W.case.data2});
Are you looking to take all of the fields under W.case and make them into top-level fields ? If so then
d = cell2struct(struct2cell(W.case),fieldnames(W.case));
2 comentarios
Más respuestas (1)
Kristoffer Clasén
el 30 de Nov. de 2020
2 comentarios
Walter Roberson
el 30 de Nov. de 2020
I suspect that you oversimplified, as what you posted should work. Each time you are assigning on a struct whose fields have been created in the same order and there are the same number of fields with the same name. That would work.
What would not work would be if you had lifted the multiple fields resulting in data.a (because load creates one field per variable) into distinct fields.. e.g. if you had used the kind of cell2struct discussed above.
If you are creating fields within data that are named after dynamic fields, then in order to use those directly at the struct array level, you would have to have all of the field names stored for all the array elements. Such a thing could be done, but would it be a good idea, compared to pushing the dynamic parts one level lower in the struct array where it would not be complained about?
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!