フィルターのクリア

How to programmatically modify substructure with arbitrary number of levels?

8 ビュー (過去 30 日間)
I am trying to create a function that can modify a field in an arbitrary deep structure in the following way:
function modified_struct = modify_field(original_struct, field_name_cell_aray, new_value)
For instance if I have an original_struct such that
original_struct.a.b = 1
calling
modified_struct = modify_field(original_struct, {'a', 'b'}, 2)
would create the following operations
modified_struct = original_struct
modified_struct.(a).(b) = 2
This should work for a struct with an arbitrary number of levels:
modified_struct = modify_field(original_struct, {'a', 'b', 'c', 'd'}, new_value)
I want a solution that does not use the eval() command since I need to use this in a parfor loop.
Is this possible in matlab?

採用された回答

Stephen23
Stephen23 2022 年 4 月 13 日
編集済み: Stephen23 2022 年 4 月 13 日
I would not write a function for this, just use SETFIELD with a comma-separated list:
S.a.b = 1;
C = {'a','b'};
N = 2;
S = setfield(S, C{:}, N);
Checking:
S.a.b
ans = 2

その他の回答 (1 件)

Jean-Baptiste Lanfrey
Jean-Baptiste Lanfrey 2022 年 4 月 13 日
If I understand correctly, all you need is to use the setfield command, for example:
modified_struct = setfield(original_struct, 'a', 'b', 2)
The field arguments are not in a cell array but I guess it is easy enough to accomodate for this.

カテゴリ

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

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by