Constructing names of array and structure variables

조회 수: 4 (최근 30일)
z8080
z8080 2021년 8월 12일
댓글: z8080 2021년 8월 13일
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!

채택된 답변

Stephen23
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.
  댓글 수: 1
z8080
z8080 2021년 8월 13일
Thank you very much Stephen, you are right that my approach was quite suboptimal, and my description of it was inaccurate also. I've learnt something valuable from your answer.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by