Problem with function handle on Root Bracketing
3 views (last 30 days)
Show older comments
Eligijus Rupsys
on 16 Mar 2020
Commented: Eligijus Rupsys
on 17 Mar 2020
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 !
4 Comments
Accepted Answer
Steven Lord
on 16 Mar 2020
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
5 Comments
Steven Lord
on 17 Mar 2020
End the lines inside the if statement with a semicolon to suppress their output from being displayed in the Command Window. See the entry for semicolon in the table on this documentation page.
Since it seems like you're relatively new to MATLAB you might find the MATLAB Onramp course that's available from the Tutorials section on the Support section of the MathWorks website (click Support on the top of this page) useful. It's a free two hour course that teaches the essentials of how to work with MATLAB, and I think you might learn even more about how MATLAB works from it.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!