Copying structure to structure
254 views (last 30 days)
Show older comments
Kristoffer Clasén
on 9 Nov 2020
Commented: Kristoffer Clasén
on 30 Nov 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 Comments
Accepted Answer
Walter Roberson
on 9 Nov 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 Comments
More Answers (1)
Kristoffer Clasén
on 30 Nov 2020
2 Comments
Walter Roberson
on 30 Nov 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?
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!