define function that includes number of variable and call it in many callback function in GUI
1 次查看(过去 30 天)
显示 更早的评论
Hi Sorry question maybe not clear so i add more details about my problem.
I have a problem in my GUI, the problem is i have 5 variables that i defined them and i use them many times in my code because they define for me important parameters. so I would like to write them in one function then i will recall the function in the wanted callback functions in order to simplify my code.
Thanks in advance
0 个评论
采纳的回答
Elias Gule
2016-4-29
Let's assume you have defined these variables. a = 2; b = 7; c = 15; Name = 'My Name'; Age = 105; To make sure that these are defined exactly as they are in a calling function we can then define our callee as:
function get_variables()
command = ['a=2;b=7;c=15;Age=135;Name=''My Name'';'];
evalin('caller',command);
end
0 个评论
更多回答(1 个)
Stephen23
2016-4-29
编辑:Stephen23
2016-4-29
Note that avoiding using evalin (or assignin, etc) has numerous advantages: it is faster, it does not overwrite preexisting values without warning, it does not make variables "magically" pop into existence in a workspace, it makes debugging much easier, it makes checking which variables have been defined much simpler, it makes adding (or setting) variable values simpler, etc,etc. Here are two simple solutions without slow and buggy evalin.
Solution One: Hardcoded Values
function S = myConst()
S.a = 2;
S.b = 7;
S.c = 15;
S.name = 'My Name';
S.age = 105;
end
When you call this function it will return a structure with all of the given variables in it. This is trivial to use:
S = myConst();
S.a % use the |a| value
Solution Two: Settable Values
function val = myConst(name,val)
mlock
persistent S
if isempty(S)
S = struct();
end
switch nargin
case 0
val = fieldnames(S);
case 1
val = S.(name);
case 2
val = S.(name) = val;
end
end
This function lets you set and get any values that you wish:
>> myConst('a',2); % set 'a' value
>> myConst('b',7); % set 'b' value
>> myConst('c',15); % etc
>> myConst('name','My Name');
>> myConst() % list all values stored in the function
ans =
a
b
c
name
>> myConst('c') % get the value of any variable
ans = 15
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!