Constructing names of array and structure variables
4 次查看(过去 30 天)
显示 更早的评论
I'm trying to dynamically create variable names, for array and struc variables. However, my usual way (below) does not work, as the brackets and dots used in the names of struc array variables are not accepted:
>> varName = genvarname ( ['a(i,j).sampleNo' num2str(n) ] )
varName =
'a0x28i0x2Cj0x290x2EsampleNo2'
>> varToPlot = eval(varName)
Error using eval
Unrecognized function or variable 'a0x28i0x2Cj0x290x2EsampleNo2'.
Any suggestions? Thanks!
0 个评论
采纳的回答
Stephen23
2021-8-12
编辑:Stephen23
2021-8-12
"I'm trying to dynamically create variable names, for array and struc variables"
But your example shows you changing a structure fieldname, not a variable name. So your description does not match your example. It is not clear what you mean by "structure variables" as all structures are arrays, just like every other fundamental data type in MATLAB:
In any case, your EVAL-approach is slow, very ill-advised, counter-productive, and best avoided: https://en.wikipedia.org/wiki/Anti-pattern
The neat, simple, and very efficient MATLAB approach for the example you show is by using a dynamic fieldname:
For example:
F = sprintf('sampleNo%d',n);
varToPlot = a(i,j).(F)
Numbered fieldnames indicates poor data design which would be more efficiently accessed using indexing.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!