Creating Variable Names from Strings

Is there a way to create a Variable with the name of a String?
I would like to do something like this:
name = "VariableName" % String containing the name I want to give it
Variable(name) = 35
And then have a Variable called Variable Name, that contains data

2 件のコメント

Dyuman Joshi
Dyuman Joshi 2024 年 1 月 20 日
That is not a good idea, explained in length (,depth and breadth) here - TUTORIAL: Why Variables Should Not Be Named Dynamically (eval)
Why do you want to do that?
Stephen23
Stephen23 2024 年 1 月 20 日
編集済み: Stephen23 2024 年 1 月 20 日
"Is there a way to create a Variable with the name of a String?"
Yes, if you really want to force yourself into writing slow, complex, inefficient, obfuscated code that is fragile and hard to debug:
However in almost all threads on this forum (and others) related to this topic, creating such variable names dynamically was not a good approach and was easily replaced by much better data design, leading to much better code.
Usually some basic indexing is quite sufficient.
Your question is a good example of this:
The most important question is: how are you planning on processing this data? What is the actual goal that you are trying to achieve?

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

 採用された回答

Taylor
Taylor 2024 年 1 月 23 日

0 投票

As other users have stated, it is generally not advisable to dynamically generate variable names from a string using eval. However, it is possible to do this with structure field names specifically.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

製品

リリース

R2022b

質問済み:

2024 年 1 月 20 日

回答済み:

2024 年 1 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by