问题
Suppose I have a function f = @(x) myfun(x)
;
I can use fzero to get the solution closest to a given x0
, but can I get all solutions in a specific area, for instance: -5 < x < 5
?
I.e. Is it possible to get a solution similar to the result of roots, but for non-polynomials?
回答1:
Yes, you can.
There's a nice submission on the file exchange that allows you to do exactly that. It works by approximating your curve by a Chebychev polynomial, and then finding all real roots of that polynomial.
If you want you can use these estimates for the roots as initial values for fzero
, but often (at least for smooth and otherwise well-behaved curves) the accuracy demands can already be met by using a higher-order Chebychev approximation.
For your example, using only 18 function evaluations (I have a slightly modified version of the file, but the essence is the same):
>> f = @(A) 17.7*sin(A).*cos(A)+87*sin(A).^2-9.65*cos(A)-47*sin(A);
>> R = FindRealRoots(f, -5,5, 17)
R =
-3.709993256346244
-3.345207732130925
-0.201929737187637
0.572382702285053
2.573423209113534
2.937157987217741
>> R2 = R;
>> funcCount = 0;
>> for ii = 1:numel(R)
[R2(ii), ~,~, output] = fzero(f,R2(ii));
funcCount = funcCount + output.funcCount;
end
>> max(abs(R2(:)-R(:)))
ans =
8.564253235401331e-004
>> funcCount
ans =
46
e.g., there is only 8 parts per ten thousand improvement for no less than 46 additional function evaluations.
回答2:
First there is Matlab's built in option that uses the symbolic math toolbox: mathworks.com/help/symbolic/mupad_ref/numeric-realroots.html
Another option, if your function is well behaved, is just to feed fsolve
with the right guesses, so even though it is using a loop, it is an efficient computation. For example:
A=linspace(-5,5,1000);
f=@(A) 17.7.*sin(A).*cos(A)+87.*sin(A).^2-9.65*cos(A)-47*sin(A)
idx = find(diff(sign(f(A))));
for n=1:numel(idx)
r(n)=fzero(f,A(idx(n)))
end
r=
-3.709541990613713
-3.345170894638306
-0.202018624930518
0.572128202319968
2.573643316565874
2.938014412541281
来源:https://stackoverflow.com/questions/16809744/is-it-possible-to-get-several-solutions-to-an-arbitrary-equation-in-matlab