passing a variable name to a function

43 次查看(过去 30 天)
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 个评论
Steven Lord
Steven Lord 2020-9-4
Can you do this? Yes.
Should you do this? The general consensus is no.
nathan blanc
nathan blanc 2020-9-5
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".

请先登录,再进行评论。

采纳的回答

Jeff Miller
Jeff Miller 2020-9-6
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by