MATLAB Answers

passing a variable name to a function

4 views (last 30 days)
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


Steven Lord
Steven Lord on 4 Sep 2020
Can you do this? Yes.
Should you do this? The general consensus is no.
nathan blanc
nathan blanc on 5 Sep 2020
many thanks for both your answers. i extended the question a bit, to explain what i am trying to do. i wonder if there is a different to do it without using "eval".

Sign in to comment.

Accepted Answer

Jeff Miller
Jeff Miller on 6 Sep 2020
You can use 'strings in parentheses' to address object and structure fields, so I think you can simply replace
obj.(Guesses{i}) = guessvalue(i);
or something very close to that.

  1 Comment

nathan blanc
nathan blanc on 6 Sep 2020
amazing,just what i was looking for!

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!