フィルターのクリア

How to access struct member via a string

13 ビュー (過去 30 日間)
Danny
Danny 2023 年 10 月 5 日
編集済み: Bruno Luong 2023 年 10 月 6 日
Let's say I create a struct via the following:
airplane.cockpit.controls.throttle = 'forward'
airplane = struct with fields:
cockpit: [1×1 struct]
I can access those fields like this:
airplane.('cockpit').('controls')
ans = struct with fields:
throttle: 'forward'
Is it possible to use these semantics but with a string representation? I've tried this:
s = "('cockpit').('controls')"
s = "('cockpit').('controls')"
airplane.(s)
Unrecognized field name "('cockpit').('controls')".
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 件のコメント
Stephen23
Stephen23 2023 年 10 月 5 日
編集済み: Stephen23 2023 年 10 月 5 日
"Is it possible to use these semantics but with a string representation?"
Not easily. But you can easily use SPLIT and GETFIELD.

サインインしてコメントする。

採用された回答

Matt J
Matt J 2023 年 10 月 5 日
編集済み: Matt J 2023 年 10 月 5 日
Here is something simiilar:
airplane.cockpit.controls.throttle = 'forward';
s={'cockpit','controls'};
getfield(airplane,s{:})
ans = struct with fields:
throttle: 'forward'
  2 件のコメント
Fangjun Jiang
Fangjun Jiang 2023 年 10 月 5 日
airplane.cockpit.controls.throttle = 'forward';
s = "('cockpit').('controls')";
pth=extractBetween(s,"'","'");
getfield(airplane,pth{:})
ans = struct with fields:
throttle: 'forward'
Danny
Danny 2023 年 10 月 5 日
Thank you! This is very close to what I was looking for

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2023 年 10 月 5 日
編集済み: Bruno Luong 2023 年 10 月 6 日
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 = struct with no fields.
airplane = rsetfield(airplane, 'cockpit.controls.throttle' , 'forward')
airplane = struct with fields:
cockpit: [1×1 struct]
airplane.cockpit.controls.throttle
ans = 'forward'
[value success] = rgetfield(airplane, 'cockpit.controls.throttle')
value = 'forward'
success = logical
1
[value success] = rgetfield(airplane, 'cockpit.controls.alarm')
value = []
success = logical
0

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by