How to call a variable with user string input
214 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Chris
le 13 Mai 2014
Commenté : Walter Roberson
le 30 Juil 2022
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!
2 commentaires
Jorge Ignacio Cisneros Saldana
le 29 Juil 2022
Modifié(e) : Jorge Ignacio Cisneros Saldana
le 30 Juil 2022
Do you know how to do same approach without eval command for a parfor loop?.
eval(['dataset = ',variableName,';']);
Walter Roberson
le 30 Juil 2022
If you were able to do an assignment by eval() inside the body of a parfor, there would be no way for matlab to know that the variable had to be returned to the client. If it were possible at all, then it would only be useful for assigning to local variables. And if you are going to be creating local variables you might as well use dynamic field names inside a struct instead of using eval()
Remember that you can assign a struct into a cell array, and then after the parfor merge the struct. Or output a cell of names and a cell of values and then cell2struct after the parfor
Réponse acceptée
Benjamin Avants
le 13 Mai 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.
Plus de réponses (2)
Roberto
le 13 Mai 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
Voir également
Catégories
En savoir plus sur Cell Arrays dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!