You are on page 1of 5

Matlab Tutorial: Programming the Bisection Method First open MATLAB by clicking Start->Programs->MathTools-> MATLAB or there may be an icon

on your desktop with MATLABR2009a Once the MATLAB window has opened you should see a few sub-windows. The window with the ">>" is the command line window. From here you can run functions, define variables, and complete computations. Though you can do some computations here, I suggest only using it to make simple computations and run functions. Another important detail is the "Current Directory". Matlab typically opens in a predefined MATLAB folder. For this class you want to SAVE EVERYTHING TO THE Z: DRIVE. I suggest making a MATH151a folder for this class and sub-folders for each of your homework assignments, much like PIC10a or PIC10b. Once you have created a HW0 folder inside the MATH151a folder on your Z: drive go to the top of the MATLAB window. There you will see a box labeled "Current Directory". From there click the " ... " button to locate your HW0 Folder. You probably have to go MyComputer-> Z: -> MATH151a-> HW0. BEFORE YOU START any homework assignment make sure your "Current Directory" is correct. Today we are going to step through programming the bisection method learned in class on Monday. This is by no means going to teach you everything you need to know about MATLAB, but hopefully it will be enough to get your started on your homework assignments. First we need to open up an editor in which to write our function. To do this go to File>new->Blank M-File . This is where we will write our program. The general shell of a program is as follows: function [output1, output2, ...] = functionName( input1,input2, ....) % Statements end Notice some differences between this and C++. First you do not need a return statement, nor do you need to specify the data types of your input or output. Also, "%" is used for comments. Finally, there is not need for curly braces, " {, } ". Instead you must use the key word end. In MATLAB you can call your "main" function whatever you like. However, to avoid complications, I suggest saving the file name EXACTLY the same as your function name. This will allow you to call your function from the MATLAB command line. For instance in this case you should have the following in your editor. function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. end Now, before we start programming the entire function, we want to stop and think about what has to happen in one iteration of the bisection method. To review the method see: http://en.wikipedia.org/wiki/Bisection_method . In terms of MATLAB code, each iteration does the following: c = (b+a)/2; if f(a)f(c) < 0 b = c;

else a = c; end Placing this code into the function we now have. %--------------------------------------- Begin File --------------------------function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. c = (b+a)/2; if f(a)f(c) < 0 b = c; else a = c; end end %--------------------------------------- End File --------------------------To run the function, go to the command window and type: >>bisectionMethod(-1,3) and then press enter. However, this will not run. Why? The function "f" has not been defined. Luckily there is an easy way to do this. We can just define another function below the main in the following: %--------------------------------------- Begin File --------------------------function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. c = (b+a)/2; if f(a)*f(c) < 0 b = c; else a = c; end end function y = f(x) y = exp(-x) - x^2; end %--------------------------------------- End File --------------------------You should run the program to see if it works. It does not...why? Once you've figured out the bug, now think about the loop. We want this to continue indefinitely until the function value at a known point is less than some tolerance, "epsilon" or we have hit the maximum number of iterations. The fact we want to run this indefinitely indicates we want to use a while loop. To know how many times this program has run, we need to have a counting variable. Let's call it NumIt. If NumIt>MaxIt and if "abs(f(c))<epsilon" we want to stop the loop.

In terms of code, it will look like: %--------------------------------------- Begin File --------------------------function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. MaxIt = 1000; epsilon = 10^-6; % Machine precision is around 10^-16 NumIt = 0; while NumIt< MaxIt && f(c)==epsilon c = (b+a)/2; if f(a)*f(c) < 0 b = c; else a = c; end NumIt = NumIt + 1; end end function y = f(x) y = exp(-x) - x^2; end %--------------------------------------- End File --------------------------There are two bugs in the code: one logical the other compile. What is the logical error and why is it a problem? The correct code should look like: %--------------------------------------- Begin File --------------------------function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. MaxIt = 1000; epsilon = 10^-6; % Machine precision is around 10^-16 c = (b+a)/2; NumIt = 0; while NumIt< MaxIt && abs(f(c))>epsilon if f(a)*f(c) < 0 b = c; else a = c; end NumIt = NumIt + 1; c = (b+a)/2; end end function y = f(x)

y = exp(-x) - x^2; end %--------------------------------------- End File --------------------------This is working code, however after running it there is no way to verify this fact, except from the lack of compile errors. One way to show the way the function works is by storing the error at each iteration in an array and then plotting the error array. As it turns out, you will be making these kinds of graphs in many of your homework assignments. How to store arrays: Unlike C++, MATLAB is able to create dynamic arrays and matrices on the fly, in that there is no need to allocate memory directly. Accessing and changing arrays is very simple in MATLAB. There are many ways to create an array, for example here are a few ways to create an array starting at 1 and increasing by 0.1 until 2; A_1 = 1:0.1:2; A_2 = [1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2]; k = 1; for i = 1:0.1:2 A_3(k) = i; k = k +1; end A_4 = linspace(1,2,11); It is also easy to access the elements of this array. For example, to change the third element of A_2 to 5 we write A_2(3) = 5; Notice unlike C++, the indexing of the array starts at 1 . A_2 is now the array { 1 1.1 5 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2} One way to plot the errors is to change the code in the following way: The arrays in this function are in bold and italicized for clarity %--------------------------------------- Begin File --------------------------function bisectionMethod(a,b) % This function finds the root of a function between 'a' and 'b' % Many of the elements of this program will be hard coded for simplicity, you can change this if you wish. MaxIt = 1000; epsilon = 10^-6; % Machine precision is around 10^-16 approximateSolution = (b+a)/2; % This will become an array in the loop NumIt = 1; %matlab starts it's index at 1 instead of 0 while NumIt< MaxIt && abs(f(approximateSolution(NumIt )))>epsilon if f(a)*f(approximateSolution(NumIt )) < 0

b = approximateSolution(NumIt ); else a = approximateSolution(NumIt ); end NumIt = NumIt + 1; approximateSolution(NumIt) = (b+a)/2; end approximateSolution % leave out "; " to display the approximate solution array on the console iterations = 1:NumIt; % Creates a vector from 1 to NumIt % note: we want f(approximateSolution) = 0, however we will not get this exactly, but we can get close figure() plot( iterations,f(approximateSolution), 'r' ) % creates a red graph hold on % allows to plot multiple things in one figure plot( iterations,f(approximateSolution), '*k' )% creates black asterics hold off title(' Error of Bisection Method vs Iteration') xlabel(' Iteration') ylabel(' error ') end function y = f(x) y = exp(-x) - x.^2; % Use .^ for element by element operation on an array % instead of ^ because x is now a vector, can also % do multiply = .*, divide = ./ end %--------------------------------------- End File --------------------------Congratulations you have written your first program in MATLAB!! Please keep this for reference for all your subsequent homework.

You might also like