# change parameter values in anonymous function

34 views (last 30 days)
zongxian on 14 Jul 2020
Edited: madhan ravi on 15 Jul 2020
My problem is one function passing to me a Anonymous function handle, for example,
f_handle = function1(a1,a2,....)
% Assuming f_handle = @(x,y) [a*(x+y),b*(x-y)], a and be are unknown parameters
As I only get this handle, (and I know there are two unknown parameters of a and b), now I want to change (set) the parameter values of a and b, I don't know how to do it.
b=1; a=1:10;
x = 1; y =2;
for i=1:10
% how to passing a(i) and b in the anonymouos function
mm{i} = f_handle(x,y);
end
Should I redefine a anonymous function or by other way?

madhan ravi on 14 Jul 2020
Edited: madhan ravi on 14 Jul 2020
b = 1;
a = 1:10;
x = 1;
y = 2;
mm = cell(1, 10);
f_handle = @(x,y,a,b) [a*(x+y),b*(x-y)];
for ii = 1:10
mm{ii} = f_handle(x,y,a(ii),b);
end
celldisp(mm)

madhan ravi on 15 Jul 2020
n = 1; % predefined
f = @(x) x^n
F = func2str(f);
str = regexprep(F,'.*\)','');
SYM = str2sym(str);
"Input in the order of" + char(symvar(SYM))
F_handle = matlabFunction(SYM)
F_handle(2,3) % 2 assigned to n
zongxian on 15 Jul 2020
I also tried to convert it to a string, and then to an anonymous function, but it was not successful. Your way is good, but there is a problem that all variables change to input variables.
for example:
m=1;n=2;
f = @(x) x^n+m ===>
f= @(m,n,x)m+x.^n
If I just want to add a parameter? other parameter sill keep its values
m=1;n=2;
f = @(x) x^n+m ===>
m=1;
f= @(n,x)m+x.^n
Anyway, I think your method has helped me a lot.
madhan ravi on 15 Jul 2020
n = 1;
m = 2;
save m
f = @(x) x^n+m
F = func2str(f);
str = regexprep(F,'.*\)','');
SYM = str2sym(str);
syms(symvar(SYM))
clear m
subs(subs(SYM, {x,n},{2,3}))

Steven Lord on 14 Jul 2020
Once you've created an anonymous function handle that "remembers" a particular value, you cannot change that "remembered" value. You would need to recreate the function handle to change it.
n = 2;
f = @(x) x.^n; % n is locked into the value 2 at this point
y1 = f(3) % 9
n = 4;
y2 = f(3) % still 9 not 3^4 = 81
f = @(x) x.^n; % Recreating f "remembers" the new value of n
y3 = f(3) % 81
If you have a value that you want to be able to change, you should probably have the anonymous function accept it. You could, if you need a function with a specific signature, write an adapter. In the example below g accepts both x and n, while f2 and f3 fix specific values for n but make use of g to compute their results.
g = @(x, n) x.^n;
f2 = @(x) g(x, 2);
f3 = @(x) g(x, 3);

Show 1 older comment
madhan ravi on 15 Jul 2020
Steven Lord on 15 Jul 2020
In your comment you defined a new function handle F_handle. You didn't modify the existing function handle f.
madhan ravi on 15 Jul 2020
Right. I misread OPs comment. What I meant by that was there’s an alternative to overcome that problem.