MATLAB: Can you change anonymous function mid cycle

anonymous functionsMATLABmodifying functionsruffini method

Hello everyone, Is it possible to modify function in the cycle? f.e. i have function
g = @(x) x.^5+2*x.^4-5*x.^3-8*x.^2+5*x+5;
And i need to divide it every loop by (x-Const). Is it possible and if yes. Can someone pls show me how? Thanks 😉

Best Answer

g = @(x) x.^5+2*x.^4-5*x.^3-8*x.^2+5*x+5;
funs = {g};
for K = 1 : 5
roots(K) = fzero(funs{K}, rand);
funs{K+1} = @(x) funs{K}(x) ./ (x - roots(K));
end
However, think for a moment about what happens if you try x = roots(1) after the first iteration. Then because g has not changed, g(x) is 0, and at x = roots(1), x - roots(1) is roots(1) - roots(1) which is 0 and that is on your denominator... so you have a 0/0 situation.
Dividing by the root only works if you can factor out the root so that the new expression no longer generates 0 at that location. (Though, pay attention to multiple roots.) If the root you come up with is a nice integer or rational or root of one of them (e.g., sqrt(5)), then you might be able to do that using the symbolic toolbox. However, fzero is going to return in numeric form, and the symbolic toolbox is not generally going to recognize the floating point number. For example if it finds that a root is 3.23606797749979 then the symbolic toolbox is not going to recognize that as 1 + sqrt(5) and so you would have problems factoring it out of a symbolic formula that knows it in that form.