MATLAB Answers

How to call a variable with user string input

826 views (last 30 days)
Chris
Chris on 13 May 2014
Commented: Chris on 13 May 2014
Hi all,
I know this is a likely a simple problem, but am having lots of trouble...
I am trying to use an array of data (say 1x50) in a for loop from a user input that is different than the name of the array.
In other words, the user inputs something like 'example' and I need to use the data in the existing array that is named 'exampleD'
exampleD = ones(1,50); % this is an existing array
inp = input('Which dataset are you working with? ','s');
% at this point user enters the string 'example'
Missing code here (some command that will concatenate user input and the letter 'D' to get 'exampleD' which is the name of the existing variable)
for i = 1:50
fprintf(fid,'%f',exampleD(i));
fprintf(fid,',');
end
Any help is greatly appreciated!

Accepted Answer

Benjamin Avants
Benjamin Avants on 13 May 2014
Although it is often advised not to use this method, it would suit your purpose.
Once you have the user's input string and have created the variable name, you can use the eval function to access that variable.
eval(['dataset = ',variableName,';']);
the chosen dataset will now be stored in the variable 'dataset' and you can use it as per normal.
You could also store all the datasets as fields of a struct and use the variable name string to access the correct field of the struct.
  2 Comments
Chris
Chris on 13 May 2014
Thanks a ton Benjamin and Roberto. Between these last two comments I am able to write just a few lines of code to figure out my issue.

Sign in to comment.

More Answers (2)

Roberto
Roberto on 13 May 2014
Edited: Roberto on 13 May 2014
exampleD = ones(1,50); % this is an existing array
inp = input('Which dataset are you working with? ');
for i = 1:numel(inp)
% whatever
end
  1 Comment
Chris
Chris on 13 May 2014
Roberto, Thanks for your answer, but this doesn't actually seem to help. My problem lies in the fact that my script needs to call a variable with an 'incomplete' user input. -Chris

Sign in to comment.


Roberto
Roberto on 13 May 2014
exampleD = ones(1,50); % this is an existing array
inp = input('Which dataset are you working with? ','s');
% at this point user enters the string 'example'
inp = eval([inp 'D']);
for i = 1:50
fprintf(fid,'%f',inp);
fprintf(fid,',');
end

Community Treasure Hunt

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

Start Hunting!

Translated by