Automatically create variable names

28 ビュー (過去 30 日間)
FERNANDO CALVO RODRIGUEZ
FERNANDO CALVO RODRIGUEZ 2023 年 2 月 10 日
編集済み: Stephen23 2023 年 2 月 13 日
Hello!
I am trying to create variable names automatically, such as:
Name_1
Name_2
Name_3
...
Name_N
To assign a different value to each one.
Do you know how to do it, any idea?
  8 件のコメント
chrisw23
chrisw23 2023 年 2 月 13 日
may be field names are a solution
define an empty struct
myStruct = []
and add fieldnames dynamically
myStruct.(<varName>) = myVal
Stephen23
Stephen23 2023 年 2 月 13 日
@chrisw23: given the sequentially-numbered names shown in the original question, basic indexing would be simpler and much more efficient.

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

回答 (1 件)

埃博拉酱
埃博拉酱 2023 年 2 月 13 日
NameIndex=1;
Value=2;
eval(sprintf('Name_%u=%d',NameIndex,Value));
Name_1 = 2
This is possible by eval but as mentioned in the comments section, it is not recommended if there is not a very good reason.
  1 件のコメント
Stephen23
Stephen23 2023 年 2 月 13 日
編集済み: Stephen23 2023 年 2 月 13 日
The name "MATLAB" comes from "MATrix LABoratory", i.e. it is designed to work efficiently with arrays and indexing. Indexing is a MATLAB superpower. If you do not use indexing, then using MATLAB will be... difficult. The name "MATLAB" does not come from "lets store the data in lots and lots of separate variables and make our data harder to work with":

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by