Naming variables according to the values of another variable

9 ビュー (過去 30 日間)
Mia Dier
Mia Dier 2021 年 5 月 25 日
編集済み: Jan 2021 年 5 月 25 日
I have a variable
A=[1;2;5]
and I want to use the values of this variable in the name of the new variables I'm going to create: B_1, B_2 and B_5.
for k=A(1,1):A(3:1)
B_'k'= TreeBagger(.)
end
This code, however, doesn't work and I couldn't come up with a solution.
  1 件のコメント
Stephen23
Stephen23 2021 年 5 月 25 日
編集済み: Stephen23 2021 年 5 月 25 日
Formcing meta-data into variable names is one way that beginners force themselves into writing slow, inefficient, complex code that is difficult to debug. Read this to know some of the reasons why:
You should store (meta-)data in variables (not in variable names) and use basic indexing, just like MATLAB was designed for.

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

採用された回答

Jan
Jan 2021 年 5 月 25 日
編集済み: Jan 2021 年 5 月 25 日
Don't do this. Hiding indices in the names of variables is a bad programming pattern, which is avoided consequently by experienced programmers. See https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
Use array and indices or a struct instead.
for k = 1:3
B(k).index = A(k);
B(k).data = TreeBagger(.)
end
By the way, A(1,1):A(3:1) might not do, what you expect. The 2nd argument is an empty vector. Maybe you mean:
for k = A.'

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by