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

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 Comment

"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.

Sign in to comment.

 Accepted Answer

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 Comments

This leads to direction i was thinking on. The problem i have is, that i don't want to change my projectname in the code by hand everytime a new project is conducted. In the end i have multiple measurements per project and would like to store them in the "projectname" structure. Then i could refer to them like:
projectname = 'PK06'
Measurement1
PK06.measurement1
Its pretty hard to describe for me. But thanks for your reply, it's definitly more helpful then just refering to the manual.
Have a nice day, Jos.
There are multiple ways to handle this
1) Search for the projectname inside a array of structs
M(1).projectname = 'PK06'
M(1).data = 1:10
M(2).projectname = 'PK12'
M(2).data = [9 9 9]
AllProjects = {M.projectname}
CurrentProject = 'PK06'
tf = strcmpi(CurrentProject, AllProjects)
CurrentData = M(tf).data
2) Create a struct and use dynamic fieldnames (not recommended!)
M2.PK06.data = 1:4
M2.PK12.data = 9
CurrentProject = 'PK06'
if isfield(M2, CurrentProject)
CurrentData = M2.(CurrentProject).data
else
CurrentData = [] ;
end

Sign in to comment.

More Answers (1)

Jan
Jan on 19 Dec 2017
Edited: Jan on 19 Dec 2017
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

Categories

Community Treasure Hunt

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

Start Hunting!