Am I creating dynamic variable names?
2 views (last 30 days)
Recently I came across a popular thread in MATLAB Answers: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval#answer_236124
After reading this thread, I am still not sure I have created "dynamic variable names", which should be avoided as suggested in that thread.
I have a code snippet as following:
data = [1, 2, 3];
centerX = data(1);
centerY = data(2);
centerZ = data(3);
% And use these variables afterwards
Should I avoid creating those (probably dynamic) variable names, i.e., centerX, centerY, centerZ to use those data and simply/directly use data(1), data(2), data(3) instead?
Sulaymon Eshkabilov on 20 Nov 2021
What you are doing here is not dynamic variable naming. You're assigning a new variable name from your already assigned data.
This example shows the dynamic variable naming and assigning values to the dynamically named variables (U and V):
eval(['V' num2str(jj) '= jj'])
eval(['U' num2str(jj) '= ' 'V' num2str(jj) '*jj'])
Which is NOT recommended to employ.
That is equivalent to:
V = 1:5;
U = V.*V;
This one is the recommended one.