Convert character vector to evaluable expression

However, the elements in my cell array are not numerical expressions, but rather variables and struct paths. I tried using sscanf using %f, %d, or %s as formatSpecs. The first 2 returns empty arrays and the latter just returns the original character vector. This is what I am doing.
struct.field1.subfield = 5;
vec = {'struct.field1.subfield'};
sscanf(vec{1},'%s')
ans = 'struct.field1.subfield'
I want to get 5.

 採用された回答

Stephen23
Stephen23 2022 年 2 月 7 日
編集済み: Stephen23 2022 年 2 月 7 日

0 投票

S.field1.subfield = 5; % do NOT use STRUCT as a variable name.
vec = 'S.field1.subfield';
spl = split(vec,'.');
val = getfield(S,spl{2:end})
val = 5
Good data design avoids dynamically accessing the variable name (S in the above example):

1 件のコメント

Gaddiel Kamto
Gaddiel Kamto 2022 年 2 月 7 日
Thank you.
Thanks for the tutorial link as well.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by