MATLAB Matlab: Use string variable as variable name

AI Thread Summary
To use a string variable as a variable name in MATLAB, the eval function can be employed to dynamically create variables based on string inputs. For example, using eval with sprintf allows for the assignment of values to a variable whose name is defined as a string. Alternatively, the assignin function can also achieve similar results by assigning values to variables in the base workspace. Additionally, the genvarname function helps ensure that generated variable names are valid. For struct members, using dot notation with strings allows for the creation of fields without complex eval statements.
ExpoEra
Messages
2
Reaction score
0
Hello all,

How do you a string in a variable as a name for another variable? Like this:

I have a variable called "Headings", inside it is a bunch of text [time, speed, distance].
Headings = [time, speed, distance]

Now, I want to have a variable that uses the text inside "Headings" as its name with 1,2,3,4 inside. So in effect, in the end I have:
time = [1,2,3,4]

So how do I make Matlab use the text inside the "Headings" as the name for a new variable?
I hope that made sense.:rolleyes:
Thanks.
 
Physics news on Phys.org
ExpoEra said:
Hello all,

How do you a string in a variable as a name for another variable? Like this:

I have a variable called "Headings", inside it is a bunch of text [time, speed, distance].
Headings = [time, speed, distance]

Now, I want to have a variable that uses the text inside "Headings" as its name with 1,2,3,4 inside. So in effect, in the end I have:
time = [1,2,3,4]

So how do I make Matlab use the text inside the "Headings" as the name for a new variable?
I hope that made sense.:rolleyes:
Thanks.

There are two things you should do:

  • READ THE DOCUMENTATION! This is covered in there.
  • If you can't, or won't, read the docs, get Matlab to generate the necessary code for you.

You can get Matlab to generate almost any code you want. Here's a hint on how you might get Matlab to generate code suitable for your current needs.

Suppose that you have some text file, data.txt, which contains the data you talked about. For instance, the contents of data.txt might be something like the following:

Code:
Time,Value
1,2
2,2
3,4
4,6
5,7

Using the Matlab current directory window, browse to where this text file is located on your hard drive. Right-click on it and select 'Import Data'.

You'll now see a new window pop up. Since your data is in comma-separated value (CSV) form, make sure 'comma' is selected as column separator and click 'Next'.

On the next screen, make sure that 'Create vectors from each column using column names' and tick the 'Generate M-code' box also.

Click 'Finish' and you'll find that your data has been imported in just the format you asked for in the original post. You'll also notice that Matlab has generated an M-file containing all of the Matlab code that was used to import the data. Browse through the code and you'll see precisely what Matlab commands are necessary to generate variables using text data from the command line.

For instance, the M-file that Matlab generates for me when I perform the above procedure is:

Code:
function importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
%  Imports data from the specified file
%  FILETOREAD1:  file to read

%  Auto-generated by MATLAB on 17-Oct-2008 22:26:03

% Import the file
newData1 = importdata(fileToRead1);

% Break the data up into a new structure with one field per column.
colheaders = genvarname(newData1.colheaders);
for i = 1:length(colheaders)
    dataByColumn1.(colheaders{i}) = newData1.data(:, i);
end

% Create new variables in the base workspace from those fields.
vars = fieldnames(dataByColumn1);
for i = 1:length(vars)
    assignin('base', vars{i}, dataByColumn1.(vars{i}));
end

Reading through this it should be obvious how to do what you want. If you wish, you can save this M-file so that you can repeat the entire procedure for other files simply by typing

Code:
importfile(<FILENAME>)

at the Matlab command prompt.
 
Thank you for you reply and it did solve part of my problem.
But don't assume that people don't read the help documents. I spent two hours searching before I post this question.

Now, the reason I had the original problem was that my variable names is more like "R_Time_for_lalala(x){z}", and it shows up as junk. I am still struggling to delete the last 6 characters on the name first.
 
Hello,

An alternative solution to the one previously posted ( using the assignin function ) is to use the eval function to execute code which is partially specified in a string.

For example,

myvarname = 'f_x';
eval([sprintf(myvarname) '=[10 20 30]']);

Will create a variable called f_x in the workspace with values 10 20 30. Similarly you could have had the array values specified by another variable in the workspace too.

myvarname = 'f_x';
datavalues = [ 5 5 3 ];
eval( [ sprintf(myvarname) '=datavalues+1'] ); % Some arbitrary operation on datavalues

This isn't really better than using assignin but it's a bit more general and my be more suited to your problem.

Thanks
 
I figured I'd add this tidbit to the end here since it helped me a lot. If the custom-named variable you are trying to add is to be a member of a structure, you can use the notation:

str = 'structVar1';
s.(str) = 5;

This will add the field s.structVar1 to the structure s. This isn't completely relevant to the problem ExpoEra was having, but as I stumbled across this post when looking for the answer and ended up with ridiculous eval(['s.',str,' = 5;']); statements before finding the real solution, I figured I'd add this to the post for fellow newbies.
 

Similar threads

Replies
5
Views
2K
Replies
5
Views
3K
Replies
4
Views
3K
Replies
3
Views
1K
Replies
32
Views
4K
Back
Top