Create Structure from cell array with dot separation in string
9 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I am reading in data from a measurements where the signal names are imported as a 1-dimensional cell array. The respective strings in the cell array represent the signal name. The signal names have been given already an inherent "structure" themselves.
What i want to do now is to automatically create a structure in matlab based on the signal names and then associate the respective measurements which per signal are a 1-dimensional numeric array.
To clarify and give an example, two strings would be for example:
{'em1500.eta_t.x []' }
{'em1500.eta_t.y []' }
I now want to automatically create a structure like:
measurements.em1500.eta_t.x = (The measurements taken);
measurements.em1500.eta_t.y = (The measurements taken);
Does anybody has an idea how to automate that process?
Best regards
2 个评论
Stephen23
2022-6-30
编辑:Stephen23
2022-6-30
"Does anybody has an idea how to automate that process?"
Creation of invalid fieldnames cannot be "automated".
However rather than writing fragile/buggy code that forces meta-data into fieldnames, why not just simply store that meta-data as data in its own right? Then your code will be simpler, more robust, and much more efficient.
采纳的回答
更多回答(2 个)
Fangjun Jiang
2022-6-30
编辑:Fangjun Jiang
2022-6-30
If your question comes down to whether "em1500.eta_t.x" can be made a field name, then the anser is No. It is an invalid field name, just as you can't make "123 xyz" a variable name.
If you can make that name to be "em1500_eta_t_x", then you can use
MyStuct=struct('em1500_eta_t_x',rand)
To establish a multi-layer structure, you can do it directly
clear a
a=struct
a.b.c.d=1
a.b.c.d
Steven Lord
2022-6-30
s = 'em1500.eta_t.x';
f = split(s, '.')
At this point you may want to use matlab.lang.makeValidName to ensure the field names (the 'pieces' of s) are valid identifiers.
mydata = setfield(struct, f{:}, 1)
mydata.em1500
mydata.em1500.eta_t
Alternately you might want to make this a table array with s as either the row name or (if you're using a release that supports table variable names that aren't valid identifiers) the variable name.
t1 = table(1, 'VariableNames', {s})
y = t1.("em1500.eta_t.x")
t2 = table(1, 'RowNames', {s})
z = t2{"em1500.eta_t.x", 1}
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!