Matlab is not recognizing variables in function handle

4 visualizaciones (últimos 30 días)
Ahmad Gad
Ahmad Gad el 31 de Ag. de 2020
Editada: Mehmed Saad el 10 de Sept. de 2020
Hello all.
I am defining a table of cells that contains function handles.
Why MATLAB cannot recognize them? He cannot access them. I am getting error that MATLAB is not recognizing the variable SS although it is defined. I get error when I type this.
a = P.fw{4}(1:10)
On the other side, when I type this,
a = @(x) 2*SS(4)*x.^0/(BI.L(4))^2
I get answer without error. Any idea why this is happening?
Thanks all.

Respuesta aceptada

Mehmed Saad
Mehmed Saad el 31 de Ag. de 2020
Editada: Mehmed Saad el 10 de Sept. de 2020
Run following two codes and learn the difference

Code-1 (error will be generated)

clear
fw = {@(x) x+SS;@(x) x+SS+1};
P = table(fw);
%%%%%%%%%%%%%
SS = 1;
%%%%%%%%%%%%%
P.fw{1}(1)

Code-2 (Works fine)

clear
%%%%%%%%%%%%%
SS = 1;
%%%%%%%%%%%%%
fw = {@(x) x+SS;@(x) x+SS+1};
P = table(fw);
P.fw{1}(1)
Also read this comment
  2 comentarios
Ahmad Gad
Ahmad Gad el 31 de Ag. de 2020
I understood the trick now. Thanks a lot for the help.
However, I don't need to type the functions in the script file. I need to define them in an input variable P. Can I define them in a variable and call (load) this variable after the SS variable has been assigned a value? MATLAB doesn't accept that idea too.
Any workaounds?
Thanks!
Steven Lord
Steven Lord el 31 de Ag. de 2020
The following will error because varToRemember didn't exist when f was defined and isn't a function that f can call when it is called.
clear varToRemember
f = @(x) x.^varToRemember;
f(3) % will error
Even if we define varToRemember after f was defined, since it didn't exist when f was defined f can't use it.
varToRemember = 2;
f(3)
If the variable exists when the anonymous function is defined, that value will be remembered and used even if the variable changes or is cleared after the anonymous function is defined.
g = @(x) x.^varToRemember;
g(3) % 9, since g "remembers" the value of varToRemember
varToRemember = 3;
g(3) % still 9 not 27
clear varToRemember
g(4) % 16, g remembers
If you want to define an anonymous function that doesn't remember a variable but obtains its value when the anonymous function is evaluated, make that variable an input. Later on you could define a second anonymous function that fixes a value for that input like k fixes varToRemember = 2 when it calls h.
h = @(x, varToRemember) x.^varToRemember;
v = 2;
h(5, v) % 25
k = @(x) h(x, v);
k(6) % 36

Iniciar sesión para comentar.

Más respuestas (0)

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by