How can I use dynamic field names instead of setfield inside a function call?

In the following call, I have an existing structure Syst0. I want to call a function with as an argument Syst0 with a field set to a value:
HwErr1 = TracePeriodicSys(setfield(Syst0,'AngleError',Err1));
This line generates a yellow caution triangle with the note "Use dynamic fieldnames with structures instead of SETFIELD". How do I do this without creating a temporary structure (e.g.,
SystTemp=Syst0;SystTemp.AngleError=Err1;HwErr1 = TracePeriodicSys(SystTemp);
I think maybe this caution is erroneous.

4 Comments

There is a subsasgn equivalent but it is pretty messy.
Most of the times that I encounter setfield, it is in the form
variable = setfield(variable, fieldname, value)
and that is the kind of code that the caution is intended to address.
Using side effects the way you do is not recommended, but it is legal.
Thanks for the quick response! I am, though, puzzled about your comment that this is "using side effects". Can you explain further? I thought this was a straightforward application of setfield.
The side effect is in the temporary variable that MATLAB creates.
Your code is equivalent to
HwErr1 = TracePeriodicSys(subsasgn(Syst0, struct('type', '.', 'subs' {'AngleError'}), Err1));
This does not modify Syst0: it creates a temporary variable to do the assignment into, and passes the result as output.
Thank you much for that explanation. It sounds like using setfield in the way I did doesn't necessarily save time or memory, but at least the code is a little easier (for me, anyway) to read.

Sign in to comment.

Answers (0)

Asked:

on 17 Oct 2019

Commented:

on 17 Oct 2019

Community Treasure Hunt

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

Start Hunting!