Naming a structure with a string that was fetched through x=input(prompt)

1 回表示 (過去 30 日間)
Maximilian Laurs
Maximilian Laurs 2017 年 12 月 19 日
コメント済み: Jos (10584) 2017 年 12 月 20 日
My code looks like this so far:
prompt = 'What is the name of your project? '
% projectname becomes the entered string
projectname = input(prompt,'s')
% a structure with the string as name should be generated
projectname = struct()
Unfortunatly the name of the structure stays "projectname" and won't become the string.
Thanks for anything that might help.
  1 件のコメント
Stephen23
Stephen23 2017 年 12 月 19 日
編集済み: Stephen23 2017 年 12 月 19 日
"Unfortunatly the name of the structure stays "projectname" and won't become the string"
That is exactly what it should do. Magically creating variable names is slow, buggy, makes code complex and hard to debug. Read this to know more:
What you are doing now keeps your meta-data (project name) out of the code, which is the best way to write code. You should not mix your meta-data into your code.

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

採用された回答

Jos (10584)
Jos (10584) 2017 年 12 月 19 日
You do not want to do that. It should be the contents of a variable that is flexible and not the name. Assuming you want to store some data for this project you could use the following approach
M.projectname = input('What is the name of the project','s')
M.data = cumsum(randi(10,1,15)) ;
% and then for instance
plot(M.data,'bo-') ; title(M.projectname)
  4 件のコメント
Maximilian Laurs
Maximilian Laurs 2017 年 12 月 20 日
There it is!
Thank you very much!
Jos (10584)
Jos (10584) 2017 年 12 月 20 日
My pleasure. Have nice day too!

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

その他の回答 (1 件)

Jan
Jan 2017 年 12 月 19 日
編集済み: Jan 2017 年 12 月 19 日
Naming variables dynamically is a bad programming style. It causes more troubles than it solves. An exhaustive summary of the large number of corresponding discussions in the forum: http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

カテゴリ

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