Matlab: Use string variable as variable name

In summary, you can use the assignin function in Matlab to generate a variable called myvarname with the values 5, 5, 3.
  • #1
ExpoEra
2
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.:uhh:
Thanks.
 
Physics news on Phys.org
  • #2
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.:uhh:
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.
 
  • #3
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.
 
  • #4
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
 
  • #6
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.
 

1. How do I use a string variable as a variable name in Matlab?

In order to use a string variable as a variable name in Matlab, you can use the "eval" function. For example, if your string variable is called "var_name" and you want to assign it a value of 5, you can use the command "eval([var_name ' = 5'])". This will create a variable called "var_name" with a value of 5.

2. Can I use a loop to create multiple variables with string variable names?

Yes, you can use a loop to create multiple variables with string variable names. You can use the same "eval" function as mentioned in the previous question inside a loop to create and assign values to multiple variables with different string variable names.

3. Is it possible to convert a string variable into a regular variable in Matlab?

Yes, it is possible to convert a string variable into a regular variable in Matlab. You can use the "str2num" function to convert a string variable into a numerical variable, and the "str2double" function to convert a string variable into a double variable.

4. How do I access the value of a variable with a string variable name?

In order to access the value of a variable with a string variable name, you can use the "eval" function to evaluate the string variable and return its value. For example, if you have a string variable called "var_name" and you want to access its value, you can use the command "eval(var_name)".

5. Is it possible to use a string variable as a subscript in Matlab?

Yes, it is possible to use a string variable as a subscript in Matlab. You can use the "subsref" function to access elements of a variable using a string variable as a subscript. For example, if you have an array called "data" and a string variable called "index" with a value of "2", you can use the command "subsref(data, struct('type', '()', 'subs', {index}))" to access the element at index 2 of the "data" array.

Similar threads

  • MATLAB, Maple, Mathematica, LaTeX
Replies
2
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
12
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
3K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
3K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
32
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
983
  • MATLAB, Maple, Mathematica, LaTeX
Replies
13
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
2
Views
2K
Back
Top