Matlab input string as variable name (or other ways)

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 4K views
ghostyc
Messages
25
Reaction score
0
Hi,

I am writing a Matlab function(script), which take some input.

I have several datasets in the workspace, say dataset1,dataset2,dataset3, ect

In my function, I have tried to use

data = input('Please input your dataset', 's')

and then use 'data' as a variable for some computation, say

sum(data);
mean(data);

It does not work. I wonder what's the 'correct' way to do it?

=====================================================

OR, I can add an argument in myfunction, say

function y = myf(ds,para)

use 'ds' to indicate the dataset that i want to use.

However, in this case, how should i use 'fminsearch' for optimization?
'fminsearch' will then treat this 'ds' input as a parameter.

=====================================================

Thanks!
 
Physics news on Phys.org
No, that is not possible. You cannot take the variable name as input. Use either switch-case or if-else:
Code:
choice = input('Enter dataset number: ');
syms data;
switch choice
    case 1
        data = dataset1;
    case 2
        data = dataset2;
    %so on...
end
Then use "data" as your variable.
 
ghostyc said:
Hi,

I am writing a Matlab function(script), which take some input.

I have several datasets in the workspace, say dataset1,dataset2,dataset3, ect

In my function, I have tried to use

data = input('Please input your dataset', 's')

and then use 'data' as a variable for some computation, say

sum(data);
mean(data);

It does not work. I wonder what's the 'correct' way to do it?

The original post was from 7 years ago, but for the benefit of anyone else:

eval() takes a string argument and executes it as code.

It is of course necessary to check that the input string is the name of a variable before executing it, as the example on that page shows (but without telling the user that they've done something wrong).

Code:
datasetName = input('Please input your dataset', 's')

if(exist(datasetName, "var"))

   data = eval(datasetName)

else

   error("There is no variable called %s", datasetName)

end
 
  • Like
Likes   Reactions: Wrichik Basu and Greg Bernhardt