Problem with function handle on Root Bracketing
显示 更早的评论
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 个评论
Geoff Hayes
2020-3-16
Eligijus - when does your code become faulty? Is it the line that you have commented out? If so, then that is the line that you call from the command line like
>> [x_1, x_2] = 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)
You don't want to be calling test_4 from withinn test_4 (since the function, in this case, is not recursive).
darova
2020-3-16

Eligijus Rupsys
2020-3-17
Eligijus Rupsys
2020-3-17
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!