Using 'for loop' on a function call

3 views (last 30 days)
Eligijus Rupsys
Eligijus Rupsys on 17 Mar 2020
Commented: Eligijus Rupsys on 17 Mar 2020
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

BobH
BobH on 17 Mar 2020
Edited: BobH on 17 Mar 2020
If you want to iterate along x_min and x_max, you can use a single counter in your for loop
for i = 1 : length(x_min) % both vectors are same length, so pick either
[root, n_iter] = Bisection(f, x_min(i), x_max(i), tol)
end
If you want to do them all at once, and eliminate the loop
[root, n_iter] = arrayfun(@(M,X) Bisection(f, M, X, tol), x_min, x_max);
This creates an array of results
root
root =
0.4022 2.0007 3.3126 4.6263
n_iter
n_iter =
17 15 14 14
  3 Comments
Eligijus Rupsys
Eligijus Rupsys on 17 Mar 2020
Thank you BobH and Stephen, you really helped me out here ! Very much appreciate your time taken to help me out !! Now my code works flawlessly !

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!