Using 'for loop' on a function call
Show older comments
Hello everyone !
Hope everyone is safe and healthy considering what is happening around the world.
I'm writing a code to find the multiple roots of a function by the Bisection method. How I'm trying to approach it, is to create a for loop on a function call, so that the Bisection method script iterates one set of x-values where there is a root, displays the root and how many iterations it took to calculate it and moves on to the next set. What I can't seem to figure out is how to make the Bisection method function to iterate multiple time for different sets of x-values.
Here is the main body of my code
f = @(x) sin(((2/9)+2)*(x-(2/4)))-3.*(((x-((2+5)/2)).*(x-((2-5)/2)))/((2/2)^2+(10-2/2)^2))
x_min = [0.4000, 2.0000, 3.3000, 4.6000] % Between the consequtive pairs of x_min and x_max there is a root
x_max = [0.5000, 2.1000, 3.4000, 4.7000]
tol = 1E-6
for i = 1 : length(x_min) && z == 1 : length(x_max)
[root, n_iter] = Bisection(f, x_min, x_max, tol)
end
And here is the script for the bisection method function
function [root, n_iter] = Bisection(f, x_min, x_max, tol)
x1 = x_min; % assign left boundry
x2 = x_max; % assign right boundary
f1 = f(x1);
f2 = f(x2);
n_it = 0; % Initiate iteration counter
err = abs((x2 - x1)/(x1 + x2)); % Compute initial error estimate
while err > tol % Termination ciretiron
xr = (x1 + x2)/2; % Find mid-point
fr = f(xr); % Evaluate function at mid-point
if f1*fr < 0 % Check which half has the root and assign variables
x2 = xr;
f2 = fr;
else
x1 = xr;
f1 = fr;
end
n_it = n_it + 1; % Increase iteration counter
err = abs((x2 - x1)/(2*xr)); % Calculate an estimate error
end
root = (x1 + x2)/2; % Calculate approximation to the root
n_iter = n_it;
disp(['You found a root! It is at x = ', num2str(root), ' , great!'])
disp(['The number of iterations taken to find the root is ', num2str(n_iter), '.'])
Thank you for taking your time reading my problem !
Accepted Answer
More Answers (0)
Categories
Find more on Startup and Shutdown 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!