Use string name as variable name for struct

12 ビュー (過去 30 日間)
Alan Khalik
Alan Khalik 2022 年 2 月 14 日
コメント済み: Alan Khalik 2022 年 2 月 14 日
I've got field names of a struct that are:
data.A__B__C
data.A__B__D
I want to make a new struct as such:
newData.A.B.C. = data.A__B__C
newData.A.B.D = data.A__B__D
I want to make new fields for my structs as follows:
names = fieldnames(data)
newNames = strrep(names,'__', '.')
for k = 1:length(names)
newData.(newNames{k,1}) = (data.(names{k,1}));
end
but I can't use the strings as fields for a new struct. I have to type every new variable by hand, of which I have over 100.
Is there some way that I can use the "newNames" variable to define a new struct with proper fields, instead of just 1 field with underscores?
  2 件のコメント
KSSV
KSSV 2022 年 2 月 14 日
Note that in the line:
newData.A.B.C.
A.B.C. is not a filed name, it is a structure again.
Alan Khalik
Alan Khalik 2022 年 2 月 14 日
yes, I want to create new fields for a structure. In
data.A__B__C
there is only 1 field: A__B__C, but I want to add new fields: A.B.C. I need this for compatibility with another function that I want to use.

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

採用された回答

Stephen23
Stephen23 2022 年 2 月 14 日
編集済み: Stephen23 2022 年 2 月 14 日
D.A__B__C = 0.5;
D.A__B__D = pi
D = struct with fields:
A__B__C: 0.5000 A__B__D: 3.1416
F = fieldnames(D);
C = regexp(F,'_+','split');
Z = struct();
for k = 1:numel(F)
Z = setfield(Z,C{k}{:},D.(F{k}));
end
Z.A.B
ans = struct with fields:
C: 0.5000 D: 3.1416
KSSV's comment here is very important to understand, and explains why your approach does not work:
You incorrectly tried to create one long fieldname with dots in it. But in reality, you are trying to define nested structures, and each structure has its own fieldnames, they do not "share" one fieldname as you were attempting. The dots are not part of a fieldname.
  1 件のコメント
Alan Khalik
Alan Khalik 2022 年 2 月 14 日
Thanks a lot. I see what I was doing wrong!

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by