Borrar filtros
Borrar filtros

Evaluating function handles without writting inputs

1 visualización (últimos 30 días)
pooya azizi
pooya azizi el 6 de Abr. de 2024
Respondida: Rik el 9 de Abr. de 2024
Hi. I want to write a code that call some function handles from another code. after loading them,I want to evaluate them (means that substitute the amount of inputs in function handles) accoeding to inputs introduced at the first lines of code.
because the number of function handles is large, I prefer to call and evaluate them only with the name of functions not by name and inputs, although the inputs have introduced before (all functions have inputs). a simple example is:
x=5;y=10;
f=@(x,y) x.^2+y.^2;
now evaluate f only with calling name not inputs. for example
eval(f)
Does anyone have any suggestions for this؟
  7 comentarios
pooya azizi
pooya azizi el 6 de Abr. de 2024
I answered your questions. Please look above
Shadow
Shadow el 9 de Abr. de 2024
Why don't you store your data in a structure, that can be passed around?
data.x = 3;
data.y = 2;
f = @(data) data.x^2 + data.y^2;
f(data)
ans = 13

Iniciar sesión para comentar.

Respuestas (1)

Rik
Rik el 9 de Abr. de 2024
The only way I can think of would be by wrapping the anonymous functions.
x=5;y=10;
f=@(x,y) x.^2+y.^2;
f=@() f(x,y);
phi = 1.5*pi;
g=@(phi) sin(phi)/(2*cos(phi));
g=@() g(phi);
feval(f)
ans = 125
feval(g)
ans = 2.7219e+15
If the idea is to cache the inputs, you should use normal functions with persistent variables:
x=5;y=10;
f_(x,y)
f_
ans = 125
function z=f_(x,y)
persistent p
if nargin>0
p.x = x;
p.y = y;
return
else
if isempty(p)
error('initialise function first')
end
x = p.x;
y = p.y;
end
z = x.^2+y.^2;
end

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by