# Finding Roots - Bisection Method Matlab Code

Matlab can be used to find roots of functions. One method is bisection method. We write a Matlab code to find approximate roots of functions using theories of bisection method which is a sub-topic of numerical methods subject.

## Matlab code

First, an introduction to code and variables are given as comments in the program. Then Matlab codes are written. After the code, code is explained.

In this tutorial, we are going to solve a quadratic equation, x2 - 4*x - 13 = 0

% final answer accuracy is enough for
%variable introduction
% X1 is the left point
% X2 is the right point
% X3 is the average value, otherwise X3=(X1+X2)/2
% value takes the value of function when X3 is substituted it in the function
% previousX1Value takes the value of function when X1 is substituted it in the function
% nextX2Value takes the value of function when X2 is substituted it in the function

format long;
syms x;
sym value;

f(x) = x^2 - 4*x - 13;
X1 = -2.2;
X2 = -2.1;
n=1;

while n<50
X3 = (X1 + X2)/2;
value = f(X3);
previousX1Value = f(X1);
nextX2Value = f(X2);

if ( value * previousX1Value )<0
X2 = X3;

else
X1 = X3

end

if value < 0
value = -1*value;
end

if value<0.000000000001
disp(double(X3));
end

n=n+1;

end
clear all;

#### format long

In this program, we are going to work with decimal numbers. So we should select our data as long.

#### syms x; and sym value;

We define two variables. x and value.

• syms: Create symbolic variables and function
• sym: 'sym' is used to express a symbolic value.

#### f(x) = x^2 - 4*x - 13;

We give our equation as a function of x.

#### X1 , X2 , n

We define three variables as X1, X2 and n. X1 and X2 are assumed root values of the function. Variable n is used to control the loop running times.