Add a field to an existing structure

8 views (last 30 days)
Al_G
Al_G on 8 Jan 2019
Commented: Al_G on 9 Jan 2019
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:Screen Shot 2019-01-08 at 1.21.21 PM.png
Screen Shot 2019-01-08 at 1.21.34 PM.png

Answers (1)

madhan ravi
madhan ravi on 8 Jan 2019
  9 Comments
Walter Roberson
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.
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.
Al_G
Al_G on 9 Jan 2019
Ah! Ok, that makes some sense. I'm self-taught with matlab (and programming), and still learning about its intricaies. I couldn't put my finger on what the difference was until you explained it. Many thanks, Walter!
For anyone running into a similar problem, this worked for me:
for iTrial=1:6
Events(iTrial).Efix.duration_copy = Events(iTrial).Efix.duration;
end

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!