Suppose we want to solve for multiple values of c. We can create functions for f and in each case.
for c = [2 4 7.5 11]
f = @(x) exp(x) - x - c;
dfdx = @(x) exp(x) - 1;
x = newton(f,dfdx,1); r = x(end);
fprintf('root with c = %4.1f is %.14f\n',c,r)
end
root with c = 2.0 is 1.14619322062058 root with c = 4.0 is 1.74903138601270 root with c = 7.5 is 2.28037814882306 root with c = 11.0 is 2.61086863814988
The definition of f locks in whatever value is defined for c at the moment of definition. Even if we later change the value assigned to c, the function is unaffected.
f(r)
ans =
1.7764e-15
c = 100; f(r)
ans =
1.7764e-15
This can get a little tricky, because the function is not executed or checked at definition time. You may discover an error using such a definition only later in the code.
clear c
f = @(x) exp(x) - x - c; % executes OK
c = 1; % does not change f
A call such as f(1) would create an error, since the assignment of c did not come until after f was defined.