0

Assume the variable FileName contains a string such as Name1. How do I make a variable with the name Name1?

The example 4 at this page seems to be similar, but I cant get it to work. Is it the right way to do it? http://se.mathworks.com/help/matlab/ref/genvarname.html

2
  • 2
    Generally speaking: you probably don't want to do this. Commented Feb 27, 2015 at 16:29
  • 2
    @nkjt: I agree, eval is a bad practice. Commented Feb 27, 2015 at 16:31

2 Answers 2

3

What you see in "Example 4" is accused as bad programming style. The documentation also contains a section why to avoid eval.

I would recommend a struct with dynamic field names to achieve similar.

filename='name1';
mydata=struct();
mydata.(genvarname(filename))=load(filename);

Besides better performance, you also get additional functionality when handling multiple files. For example structfun to apply a function to all your data or fieldnames to get all filenames.

Sign up to request clarification or add additional context in comments.

6 Comments

As a side note ... string filename must be a valid property name (no space, no &, start with a letter, must not be a keyword and must be less than namelengthmax ) ... Name validity can be tested with isvarname
Plus 1 for avoiding eval. I would have done the struct approach myself.
Side note also, mex function mxCreateStructArray does not test its parameters and allows creating structure with invalid field names (see this mex source)... Came across the situation no more than 3 days ago and reported this small issue to TMW.
@CitizenInsane: Added genvarname to the solution. Converts to valid variable names, which should also be a valid field name.
That code produces error message:Error using load Unable to read file 'name1': no such file or directory.
|
1

For what you want to do, the eval function is there for you:

FileName = 'Name1';
eval([FileName ' = 18;']);      % Executes "Name1 = 18;"

and now the variable Name1 is created and has a value of 18.

The function genvarname has a different purpose, which is to generate acceptable and non-conflicting variable names, and not the variables themselves.

3 Comments

How do you access the variable later in your function? For instance, if you wanted to increment Name1? You can't just do Name1 = Name1 + 1; because Name1 isn't know beforehand, right?
No, it would work since eval actually creates a Name1 variable in the workspace
How did you know to call the variable Name1 later in the function but not when you created it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.