Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab: Use string variable as variable name

  1. Oct 17, 2008 #1
    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.
     
  2. jcsd
  3. Oct 17, 2008 #2
    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 (Text):

    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 (Text):

    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 (Text):

    importfile(<FILENAME>)
     
    at the Matlab command prompt.
     
  4. Oct 17, 2008 #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.
     
  5. Nov 18, 2008 #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. Nov 24, 2008 #5
    Hi, your case depends on the version of Matlab. As far as I know, there is a function named as "genvarname " - "Construct valid variable name from string". You can refer to the following website for the answer to your problem.

    http://www.mathworks.com/access/hel...sult&cd=1&q=matlab+variable+as+string&spell=1

    Best Regards
     
  7. Nov 9, 2010 #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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Matlab: Use string variable as variable name
Loading...