using fzero with arrayfun searching for zeros inside an interval

2 views (last 30 days)
I have a function f = @(x) -x.^2+4 with a zero at -2 and +2
using fzero(f, [-3, 1.9]) I get the (correct) zero inside the interval [-3, 1.9] , which is -2
when I now have not one but multiple intervals where I want to detect zeros, let's say: [-3, 1.9] and [1.9, +3],
fzero(f, [-3, 1.9; 1.95, 3]) returns an error, telling me, that the second argument must be scalar or a vector of length 2 (= interval).
When I now try to use arrayfun in order to successively apply my intervals to fzero I get:
arrayfun(@(x) feval("fzero" , f, x), [-3 1.9; 1.95 3])
ans =
-2 2
2 2
because fzero does not take intervals, but single values.
However I would like to use intervals and the expected result should be
-2
2
I do not want to use a for loop because of performance issues.
Now the question: Can anyone help how to make "fzero" run on multiple intervals using "arrayfun" (or any other trick) ?

Accepted Answer

Ameer Hamza
Ameer Hamza on 6 Dec 2020
Create a cell array and then use cellfun()
f = @(x) -x.^2+4;
C = {[-3 1.9]; [1.95 3]};
sol = cellfun(@(x) fzero(f, x), C)

More Answers (0)

Categories

Find more on Downloads in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!