简体   繁体   中英

matlab: how to find the largest zero of a function in an interval

Given a scalar function handle f(x) defined in a closed interval [a, b] , I wish to find the largest zero, ie the large value x in [a,b] st f(x)=0 .

It seems fzero() does not support functions defined in close intervals, so starting it from fzero(f, b) leads to an error.

So I use fminbnd() with the function g=@(x) (f(x)).^2 but it does not support "initial condition" of x=b or otherwise biasing it toward the largest zero...

According to the docs, fzero() does support closed intervals, except the output values for the intervals must have different signs. So it may or may not work, depending on your function.

Documentation:

Initial value, specified as a real scalar or a 2-element real vector...

2-element vectorfzero checks that fun(x0(1)) and fun(x0(2)) have opposite signs, and errors if they do not. It then iteratively shrinks the interval where fun changes sign to reach a solution. An interval x0 must be finite; it cannot contain ±Inf.

With that said, a quick and dirty way of finding any zero crossing I like to use, is using the sign() , diff() , and find() functions:

x = -10:10; % Any interval you want
y = func(x); % Evaluate your function
d = diff(sign(y)); % Change in signs. Any non-zero values are the places (near) zero crossings
ind = find(d); % Get indices of all non-zero values
xz = x(ind); % Get x's near/at zero crossings.

You can find the largest x where f(x) = 0 by simply choosing from the biggest xz .

Now obviously, this will only give you a crude approximation, and may not be ideal depending on your task; but choose a fine enough interval to test and it should work.

Or, you can use the results of this as a starting point, and find precise values with more advanced numerical algorithms like the Newton-Raphson method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM