MATLAB: Problem with function handle on Root Bracketing

function handle

Hello everyone !
I'm trying to write a code for a graphical method of root bracketing, where the range of x values are incremented with a step size of 0.1. The script esentially has to take the two consequtive x values, compute the corresponding y values and multiply them to check if there is a change of sign, if there is, then it means that at that range of two x-values there is a root, and then it stores the x values.
I am struggling because i will later going to have to plug in this code into a bisection method code to find the actual root (that is however a problem for a later date). When i try to use 'function' and add the @(x) term (sorry i am not too confident with the terminology), i get the wrong answers. I need to figure out why im getting the wrong answers before i can move to the next stage of my script.
This is the faulty code;
function [x_1, x_2] = test_4(f, x_min, x_max)
x = x_min : 0.1 : x_max % the range of x-values with a step of 0.1
j = 0
for i = 1 : length(x)-1
if (f(i)*f(i+1)) < 0
j = j + 1
x_1(j) = (i*0.1) - 0.1;
x_2(j) = (i*0.1) + 0.1
end
end
% test_4 (@(x) sin(((2/9)+2)*(x-(2/4)))-3.*(((x-((2+5)/2)).*(x-((2-5)/2)))/((2/2)^2+(10-2/2)^2)), 0, 10)
end
And here is the code that i know works and gives me the desired & correct answers;
x_min = 0
x_max = 10
x = x_min : 0.1 : x_max
f = sin(((2/9)+2)*(x-(2/4)))-3.*(((x-((2+5)/2)).*(x-((2-5)/2)))/((2/2)^2+(10-2/2)^2))
j = 0
for i = 1 : length(x)-1
if (f(i)*f(i+1)) < 0
j = j + 1
x_1(j) = (i*0.1) - 0.1;
x_2(j) = (i*0.1) + 0.1
end
end
Looking forwards for your replies !
Thank you !

Best Answer

for i = 1 : length(x)-1
if (f(i)*f(i+1)) < 0
Do you want to evaluate your function with the loop index as input or do you want to evaluate your function with values taken from your x vector as input? What your code is doing is the former, but you probably want the latter.
x = 0:0.25:5;
for loopidx = 1:numel(x)
fprintf("Element %d of x is %f.\n", loopidx, x(loopidx))
end