MATLAB: Fzero function calculating all zeros within interval

fzeroroots

Hello,
I was thinking about the function fzero. If you have a function that has multiple roots within an interval of your choice, is there a way to show all the roots as an array, instead of only one root closest to the guess?

Best Answer

You can first get an estimate of the zeros (if any) in your interval-of-interest by calculating it in that interval, then multiplying the function by circshift of the function to detect any zero-crossings that might be present. After that, use those estimates as your initial guesses for fzero
To illustrate:
x = linspace(0,50,200);
y = @(x) sin(x);
zx = x(y(x).*circshift(y(x),[0 -1]) <= 0); % Estimate zero crossings
zx = zx(1:end-1); % Eliminate any due to ‘wrap-around’ effect
for k1 = 1:length(zx)
fz(k1) = fzero(y, zx(k1));
end