Creating Variables from Excel

4 views (last 30 days)
Richa
Richa on 29 Jul 2011
Hello all!
I am trying to make my program more user friendly by having the user view all of the variables and define their values in an excel spreadsheet, with variable names in the one column and values in another. My hope was to create global variables using those variable names, in case the row values change or variables are added/removed. While I have found many ways of getting the data into the workspace, I cannot figure out how to create these variables using the names from the spreadsheet. Is there a way to define variables from strings or am I just wasting my time?
Thanks!

Accepted Answer

Rick Rosson
Rick Rosson on 29 Jul 2011
You can use the eval command to convert a string into a variable, although I generally recommend against using eval unless absolutely necessary.
For example:
eval( [ aStr ' = ' num2str(aValue) ';' ] );
For more information:
>> doc eval
HTH.
Rick
  2 Comments
Ashish Uthama
Ashish Uthama on 29 Jul 2011
Richa, you could also consider dynamic structure field names:
aStr = 'myVar';
ssheetData.(aStr) = 1;
Walter Roberson
Walter Roberson on 29 Jul 2011
Please do not use eval! Dynamic structure names are better. See also http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

Sign in to comment.

More Answers (2)

Rick Rosson
Rick Rosson on 29 Jul 2011
As an alternative to using Excel, have you considered creating a GUI in MATLAB for the users to enter the values of these variables? How many variables are there? Are all of them scalars, or are any of them arrays?
There are in general two ways to create a GUI in MATLAB. You can either create the GUI programmatically (on-the-fly), or using a tool called GUIDE that is provided with MATLAB. Depending on how many variables and how complex of a GUI you want to create, you may find that one approach is better than the other based on your requirements.
For more information about GUIDE:
>> doc guide
HTH.
Rick

Richa
Richa on 29 Jul 2011
There are about 25 scalar inputs. The plan is to have both a gui and a spreadsheet synced together so the user can use the one they are more comfortable with, and store alternative sets of values in the spreadsheet. The spreadsheet seemed like an easier place to start. I will try out the eval command, but if that gives me trouble I will give the gui a try. Thanks!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!