MATLAB Answers


Print String Names to be used for Variable Names?

Asked by Thomas Blackwood on 1 Jun 2017
Latest activity Edited by Stephen Cobeldick on 2 Jun 2017
I have a function that lists filenames in a vertical array of strings.
fileArray = {'file1'
Say I want to assign values and have the variable titled file2. I was thinking one could do it like:
disp(fileArray{2}) = 7
to make:
file2 = 7
But this doesn't seem to work. Any alternative suggestions?


Do not do this. Although beginners sometimes imagine that magically creating variable names will solve all of their problems, in reality it just makes code buggy, slow, hard to debug, and hard to read. You might like to consider that the MATLAB documentation specifically advises against what you are trying to do: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
"Any alternative suggestions?"
Yes, use indexing. Indexing is simple, fast, efficient, neat, easy to read, makes debugging easy,...
You might also like to read what experienced MATLAB users say about this idea:
etc, etc
Ah, so just assign all my values into one mega matrix with size(fileArray) number of columns?
Sure. Use a numeric matrix, if that works for your data. Else consider a numeric ND array, or a cell array, or a table, or a structure, or...
Accessing and processing data in one array is going to be a lot simpler than trying to do the same with lots of separate variables. As a general rule of thumb keep your data together as much as possible and your code will be much simplified.

Sign in to comment.

0 Answers