Create a series of variables with names that include numbers

6 ビュー (過去 30 日間)
Rich006
Rich006 2023 年 4 月 28 日
編集済み: Stephen23 2023 年 4 月 29 日
I need to create some fake data for testing a program. The fake data is a series of variables with names like VAR004300, VAR004400, VAR004500, etc. Each variable will be a 1x1 struct with 5 fields (same 5 fields for all variables). What is the smart way to create these variables? I would like to avoid typing out the field names the same way dozens of times. The dumb way:
VAR004300 = struct('FIELD1', value431, 'FIELD2', value432, ...);
VAR004400 = struct('FIELD1', value441, 'FIELD2', value442, ...)
  3 件のコメント
Rich006
Rich006 2023 年 4 月 28 日
Thanks, but as I commented in the accepted answer, I'm trying to create a test data sample with these variable names and I was looking for an efficient way to create them all without having to type them all in.
Stephen23
Stephen23 2023 年 4 月 29 日
編集済み: Stephen23 2023 年 4 月 29 日
"I was looking for an efficient way to create them all without having to type them all in."
Sure, that was perfectly clear from your question. And as everyone here was explaining, there is no "efficient way" to do that. Not only that, forcing meta-data into variable names makes processing data much harder, slower, and buggier, so the whole approach should be avoided anyway. Which is exactly what the links you were given explain.
The simpler, easier, and much more efficient approach is to use one array. Exactly what kind of array is best depends on the specific situation.
If you really are interested in "efficient" ways of storing and working with data, then understand that meta-data is data, and that data should be stored in variables (not in variable names or fieldnames). Then you can really start to write neat, robust, efficient, generalizable code:

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

採用された回答

John D'Errico
John D'Errico 2023 年 4 月 28 日
The funny thing is, what you want to do actually is the bad way to solve the problem.
Instead, learn to use arrays. Learn to use cell arrays, instead of dynamically naming your variables.
  7 件のコメント
Image Analyst
Image Analyst 2023 年 4 月 28 日
I guess you didn't check out the FAQ like in my answer because that was shown in the FAQ. Thankfully Steve answered soon or you would have gone longer without a solution. Anyway, the FAQ is still worth looking at because there is lots of interesting other info in there.
Rich006
Rich006 2023 年 4 月 28 日
I actually did read it. I found a partial solution there, but Steven Lord's comment was more complete.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2023 年 4 月 28 日

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by