How to access struct member via a string
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Let's say I create a struct via the following:
airplane.cockpit.controls.throttle = 'forward'
I can access those fields like this:
airplane.('cockpit').('controls')
Is it possible to use these semantics but with a string representation? I've tried this:
s = "('cockpit').('controls')"
airplane.(s)
Reason for asking is that I have a configuration file that use the same structure notation to "drill" down into the structure. I'd like to be able to read that configuration file to access certain members of the struct
1 Kommentar
Stephen23
am 5 Okt. 2023
Bearbeitet: Stephen23
am 5 Okt. 2023
"Is it possible to use these semantics but with a string representation?"
Not easily. But you can easily use SPLIT and GETFIELD.
An explanation of why your approach does not work: https://www.mathworks.com/matlabcentral/answers/1656435-tutorial-comma-separated-lists-and-how-to-use-them#answer_966455
Akzeptierte Antwort
Matt J
am 5 Okt. 2023
Bearbeitet: Matt J
am 5 Okt. 2023
Here is something simiilar:
airplane.cockpit.controls.throttle = 'forward';
s={'cockpit','controls'};
getfield(airplane,s{:})
2 Kommentare
Fangjun Jiang
am 5 Okt. 2023
airplane.cockpit.controls.throttle = 'forward';
s = "('cockpit').('controls')";
pth=extractBetween(s,"'","'");
getfield(airplane,pth{:})
Weitere Antworten (1)
Bruno Luong
am 5 Okt. 2023
Bearbeitet: Bruno Luong
am 6 Okt. 2023
I made this for my own use. It is not a dot syntax, just the functional form.
The constraint is that accessing nested subfield(s) should be scalar.
Assignment automatically creates the intermediates nested structures if they do not exist.
Error handling when retreive if the intermediate/final nested structures do not exist.
airplane = struct()
airplane = rsetfield(airplane, 'cockpit.controls.throttle' , 'forward')
airplane.cockpit.controls.throttle
[value success] = rgetfield(airplane, 'cockpit.controls.throttle')
[value success] = rgetfield(airplane, 'cockpit.controls.alarm')
0 Kommentare
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!