passing a variable name to a function
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Nathan Bblanc
le 4 Sep 2020
Commenté : Nathan Bblanc
le 6 Sep 2020
let's say i have several variables, and i want to create a function that changes a variable based on user specification
for instance: a function set_to_8(var), that accepts "var" (or a string containing var's name, or anything else for that matter) as an input and sets the value of var to be 8.
is there a way to do that?
update: I decided to expand my question, to explain more what i am trying to do. all of my files are attached here as a zip file and all of the file "main_Ta_code" is the main file illustrating my example
i am working on an object oriented code for phase change thermoacoustic systems (never mind what the hell these are). for now i have written two classes- the main object "Ta_system" and an example of a system component "Ta_Round_Duct". each system has many components which could be ducts or other objects not yet written.
each component has a "run component" command and the system has a "run system" command that runs all components in order. during the run some of the properties of the system/components are changed.
now what i am trying to do is to write a function that gets the value of a system/component ps an input, runs the system and returns the value of another system parameter as an output. this is required for optimization purposes. the ultimate goal is to be able to answer the question "what value should this parameter have in order for this parameter to have that value". once i have such a function, this question is easily answered through some iterative algorithm.
based on the answers here i have written a simple function G2T that uses "eval". however, everybody seems to be really against using "eval" so i wouldnt want to base my entire code on it. is there another way to to this?
many thanks in advance to anyone brave and nice enough to try and understand my mumbles and help. i will be happy to clarify anything that is unclear in the functions or in what i wrote
Nathan
3 commentaires
Réponse acceptée
Jeff Miller
le 6 Sep 2020
You can use 'strings in parentheses' to address object and structure fields, so I think you can simply replace
eval([obj.Guesses{i},'=',num2str(guessvalue(i))])
with
obj.(Guesses{i}) = guessvalue(i);
or something very close to that.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!