For a package, I need a global config to be configured by users from Command Window and available to all package functions and classes.
I need to be able to both get and set a config setting.
Suppose that config is currently defined as:
```
config = struct();
config.stores = { ...
struct( ...
'name', 'local', ...
'type', 'file', ...
'location', '/tmp' ...
), ...
struct( ...
'name', 'external', ...
'type', 's3', ...
'access_key', 'aws_key', ...
'access_secret', 'aws_secret' ...
)
}
```
When a user makes a call to Settings('stores{2}.name'), I would like to have it return 'external'.
If a user needs to update a setting, they should be able to do so with Settings('stores{2}.name', 'aws').
To solve this, I have created a Settings function that simply provides an entrypoint into a Settings class that has a static method with a persistent struct variable, config. This works fine utilizing getfield(config, fieldPath{:}) and setfield(config, fieldPath{:}, value), however, it breaks down when accessing a field containing a cell array (as above). This is because a get such as:
fieldPath = {'stores' {[2]} 'name'};
getfield(config, fieldPath{:})
is translated to
config.stores(2).name
The exact error is "Dot indexing is not supported for variables of this type."
Unfortunately, I cannot guarantee the array will have uniform objects as this configuration is actually being loaded from an external process.
My question is: How can I dynamically index into a nested struct over fields containing cell arrays?
This is my first post, so hoping I can get any feedback and tips on best MATLAB practice to resolve such a use case. So far I have been toying with alternatives utilizing recursive loops and eval.
Many thanks in advance!
Raphael
0 Comments
Sign in to comment.