MATLAB Answers

Find Structure Field using a string and modify content of data under this field

3 views (last 30 days)
I am currently designing an app, where I want to modify the data of a 1 x 1 structure with 162 fields. The string of the fieldname can be chosen from a dropdown menu and the desired value of said field can be selected via an EditField.
So if, for example I want to change the value of the field "X" to the value "XValue"
app.ValueDropDown.Value = "X"
structure.X = Xvalue
However I want the App to change the value of roughly 50 fields, depending on what the user desires and I currently see no other way than to do that using 50 if functions.
FieldNameVariable = app.ValueDropDown.Value %The FieldNameVariable now is of type "Char"
FieldNameVariable = convertCharsToStrings(FieldNameVariable) %The FieldNameVariable now is of type "String"
if FieldNameVariable = "X"
structure.X = XValue
else FileNameVariable = "X2"
structure.x2= XValue
else FileNameVariable = "X3"
structure.x3= XValue
...
else FileNameVariable = "X50"
structure.x50= XValue
end
Not only is this quite tedious to program, by programming it this way, one does need to change the app code if a new field wants to be made avaible for change.
Does anyone know a way to select and change the values of a certain Field using a string identical to the Field-Name?
Thanks in advance

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 3 Oct 2019
Edited: Stephen Cobeldick on 3 Oct 2019
You can use dynamic fieldnames:
fld = 'X';
S.(fld) = XValue;
ADDENDUM: Given that your example fields are numbered it is quite possible that you would be much better off using a non-scalar structure with indexing:
S(k).Xvalue = XValue;
Using a non-scalar structure with indexing would allow you to set/get the values of multple structure elements at once, and take advantage of other convenient syntaxes:

  1 Comment

Joel Affolter
Joel Affolter on 3 Oct 2019
Hey Stephen,
Thanks for the super fast response, I will give it a look!
My fields are not numbered. I just used this notation to get my idea/problem across

Sign in to comment.

More Answers (0)