Calling variables using variable list in character array
30 views (last 30 days)
Show older comments
I would like to build a matrix of several variables that I have in my mat file. I have the names of all of the variables listed in a character array. I did this using the who command. Now I'd really like to form my matrix using this character array rather than calling them all individually. I'd eventually like to adapt this code to import data from my instrument weekly, and the variable names will not always be the same. They will, however, always have the structure of 't*'
Can someone help me with this?
0 Comments
Answers (1)
Evan
on 19 Jun 2013
Edited: Evan
on 19 Jun 2013
You could create a structure from the string of variable names, like so:
varNames = ['var1';'var2';'var3']; %example character array
for i = 1:size(varNames,1)
S.(varNames(i,:)) = rand; %create field and set to random number
end
Another option I can think of would be to create your variables using the "eval" command, but this is slow and not recommended: http://matlab.wikia.com/wiki/FAQ#Why_is_it_advised_to_avoid_using_the_.22eval.22_function.3F
If you were to have to do it that way, though, it would be like this:
eval(['S1 = ' varNames(1,:)])
2 Comments
Evan
on 19 Jun 2013
Edited: Evan
on 19 Jun 2013
Oops, sorry. Yeah, my first code definitely doesn't do the same as the second. I'm not sure what I was thinking.
So the only thing I can think of would be the unfortunate "eval" command as I showed. However, if you changed the way that you were loading in your data, so that it was loaded into a structure rather than into your workspace as individual variables, would that work for what you're wanting?
S = load('myVars.mat')
for i = fieldnames(S);
% do operations here
end
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!