Am I creating dynamic variable names?

6 ビュー (過去 30 日間)
hmhuang
hmhuang 2021 年 11 月 20 日
コメント済み: hmhuang 2021 年 11 月 22 日
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?
  3 件のコメント
hmhuang
hmhuang 2021 年 11 月 21 日
  • matrix1, matrix2, matrix3, matrix4, ...
  • test_20kmh, test_50kmh, test_80kmh, ...
  • nameA, nameB, nameC, nameD, ...
hmhuang
hmhuang 2021 年 11 月 21 日
編集済み: hmhuang 2021 年 11 月 21 日
@Stephen But now I understand those example given in that thread were dynamically created using eval, which is different from my hardcoded ones.

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

回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 11 月 20 日
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):
for jj=1:5
eval(['V' num2str(jj) '= jj'])
eval(['U' num2str(jj) '= ' 'V' num2str(jj) '*jj'])
end
Which is NOT recommended to employ.
That is equivalent to:
V = 1:5;
U = V.*V;
This one is the recommended one.
  11 件のコメント
Image Analyst
Image Analyst 2021 年 11 月 22 日
@hmhuang, no. He did not create the dynamically named variable. His variable names are hard coded. If the file was called foo.png, there is no variable created called foo. You could do that with eval() but as we've been discussing, that's not recommended so that's why he probably did not show it. However he's saying that some people think they want to do it because they don't realize the problems it can cause.
hmhuang
hmhuang 2021 年 11 月 22 日
That's clear now, thanks!

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

カテゴリ

Help Center および File ExchangeData Import and Analysis についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by