Add a field to an existing structure
31 views (last 30 days)
Show older comments
I have a structure called "Events", containing a field called "Efix" for each trial in my data. Efix contains a subfield called "duration" and I want to add a field that copies this duration data. I'd like the new field to be called "duration_copy".
I've tried lots of different iterations, some of which are:
>> Events.Efix.duration_copy = Events.Efix.duration;
>> Events.Efix(:).duration_copy = Events.Efix(:).duration;
>> Events.Efix.duration_copy = Events.Efix.duration{:};
For these, I receive the error: "Expected one output from a curly brace or dot indexing expression, but there were 6 results."
I also tried:
>> [Events.Efix(:).duration_copy] = Events.Efix.duration;
>> [Events.Efix(:).duration_copy] = Events.Efix(:).duration;
>> [Events.Efix(:).duration_copy] = Events.Efix{:}.duration;
For these, I receive the error: "Scalar structure required for this assignment."
What code would accomplish this?
Edited to add screenshots:
0 Comments
Answers (1)
madhan ravi
on 8 Jan 2019
9 Comments
Walter Roberson
on 9 Jan 2019
The difference is that your top level structure is non-scalar, each entry of which contains a field Efix which all happen to be scalar struct (it looks like.) The test I show was for the case of a scalar top-level struct that had a non-scalar struct Efix inside it.
The only way that might work without a loop for you is https://www.mathworks.com/help/matlab/ref/setfield.html setfield(), but my reading of https://www.mathworks.com/help/matlab/ref/setfield.html#mw_412d6afc-f292-45a8-95be-f96d6bae8fb9
Indices for S and fields 1 through N-1 specify individual elements of structure arrays. Indices for field N specify one or more elements of the array in that field, which can be of any type.
is that you cannot do it one setfield call -- because in order to do it for nonscalar S your first index would have to be to specify something that was not an individual element of the array, which is not permitted.
So I think you are going to need to use a loop.
See Also
Categories
Find more on Matrix Indexing 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!