This function is a hack and slash version of the Bisection method and Newton's method for finding a zero intersection of an inputted function, Fun, and your initial interval guess. I have no other choice in methods as my teacher explicitly stated to do so.
The function is pretty amazing in how it convergences on xsol, which is the x value at Fun=0…. But after it converges it produces oddly predictable patterns.
If x = 2 for y = 0, xsol finds x=2, but after it converges it produces xsol = -5. If x = 3, xsol = 3, and after it converged again xsol = -4.5 and so on so on x = 3, xsol = 3, but then goes to xsol = -4 after the initial convergence.
Note: my function has no safety features included as i didn't want to complicate it when asking for help. Because of this, if your if your interval is your solution it will mess up, if the derivative is 0, it will mess up, and if a value of an interval limit is zero, it will mess up. This is okay, as i can fix this later.
If none of these features are bothered, the function converges on the correct value before it goes off on a tantrum.
A quick explanation of my variables, a0 and b0 are the initial interval, tol is nothing as i deleted it for now, a is a row vector full of the new a0 interval values, b is also a row vector, but of the new b interval values and the current estimation for xsol.
Any help for explaining this odd pattern (and how to fix it) would be much appreciated!! I'm certainly not worried about function efficiency, only capabilities as I'm quite the matlab noob. If you read this far, you certainly deserve a Thank you!
%%%Script
Fun = @(x) (x-2); a0 = 5; b0 = -12; tol = 10^-6; UntitledEight(Fun,a0,b0,tol); %%Function
function UntitledEight (Fun,a0,b0,tol) fa = Fun(a0); fb = Fun(b0); if (a0 > b0) temp = a0; a0 = b0; b0 = temp; end a = [0;a0;zeros([101,1])]; b = [a0;b0;zeros([101,1])]; n = 100; for i = 2:n+2 xsol = b(i,1); if (a(i,1) > b(i,1)) temp2 = a(i,1); a(i,1) = b(i,1); b(i,1) = temp2; end m = (b(i,1) + a(i,1))/2; s = b(i,1)-(Fun(b(i,1))*(a(i,1)-b(i,1)))/(Fun(a(i,1))-Fun(b(i,1))); if (Fun(b(i,1)) == Fun(b(i-1,1))) b(i+1,1) = b(i+1,1) + m; else if (m < s && s < b(i,1)) b(i+1,1) = b(i+1,1) + s; else, b(i+1,1) = b(i+1,1) + m; end end if (Fun(a(i,1))*Fun(b(i,1)) < 1) a(i+1,1) = a(i+1,1) + a(i,1); else a(i+1,1) = a(i+1,1) + b(i,1); endendend
Best Answer