define function that includes number of variable and call it in many callback function in GUI

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Elias Gule
Elias Gule le 29 Avr 2016
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

Plus de réponses (1)

Stephen23
Stephen23 le 29 Avr 2016
Modifié(e) : Stephen23 le 29 Avr 2016
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

Catégories

En savoir plus sur Structures 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!

Translated by