M439 Numerical Analysis Lab Week One

Before you start this lab, create a folder (use Explorer) on your N: drive called M439  for this class.  

Introduction to MATLAB

m-Files in MATLAB: Scripts and Functions


Introduction to MATLAB

Numerical Analysis studies techniques for computing approximations to mathematical quantities that are not readily computed analytically (with a formula).  Mathematical computer packages use numerical methods -- including Derive, Maple and MATLAB, as well as graphing calculators.

(Start MATLAB-- then enter and execute the commands in red below)

Background
MATLAB (an abbreviation for MATrix LABoratory) is a software package supporting interactive, matrix-based numerical computation for scientific and engineering applications. In addition, it supports graphics and has a built-in high level language. It is powerful, yet easy to learn to use. The best way to learn to use MATLAB is to work with it hands-on. The following tutorial is meant to be done interactively on the computer and provides you with a brief introduction to the fundamental features of the software needed to get started in using it. Since MATLAB is available on several hardware platforms and in different versions (i.e., Student or Professional), there are some differences in the user interfaces. See Appendix A for more information.

Note: In the examples that follow in this section (as well as others), commands that you should type in at the ">>" prompt are red bold-faced. If part of the command is in italics ( for example, >> % your name ),  it represents something to be replaced by the appropriate specific value.


1. Start a session with MATLAB by choosing the MATLAB icon in the math folder. After MATLAB has been correctly started, the MATLAB desktop should appear.  You can control what windows are open on this desktop by using the Desktop Menu. 
In the Command Window, the prompt ">>" should appear. That is the signal that the MATLAB interpreter is awaiting expressions to be entered that it will evaluate.

2.  Make the N:\m439 directory your current directory in MATLAB

             Enter “N:\m439” in the Current Directory box or use the browse button to choose this.

3. Anything that is not preceded by "%" is treated as an expression to be evaluated. The user enters an expression (followed by Enter), and then MATLAB evaluates and prints the result returned to the screen.

  Enter

cos(pi/4)

4.  The fundamental data object for MATLAB is the matrix. An easy way to enter a matrix in MATLAB and to save its value in a variable is to enter

variable = [ list of each row's values separated by ;'s]

The matrix itself is returned as the value of the expression entered. A scalar value is treated as a 1 x 1 matrix and may be entered without any square brackets. Enter:

>> A = [1 2 3; 4 5 6; 7 8 9]
>> c = 10

5. You may also enter an expression without saving its value in a variable. The most recent value returned by MATLAB is saved in the system variable ans.

Try the following:

>> [1 2 3 4; 5 6 7 8]
>> ans
>> 5+2*30
>> ans

6. MATLAB is case-sensitive That is, "a" is not the same as "A", nor is "aBs" the same as "Abs" or "abs". Enter the following (the command who gives information about currently defined variables and their current values):

>> B = [0 1; 1 0]
>> b = 2.5
>> who

7. When all the entries of a matrix are integers or rational numbers, then they are displayed as such.  If one or more are entered as real (with a decimal point), then the format for the display is real (with decimal points). Enter the following:

>> format long
>> A = [1 2 3.5; 4 5 6]
>> b = 7.921
>> format short
>> A
>> b

8. On-line help is available with the help command. Enter help to get a general list of help topics, and help topic to get help on the specified topic.

>> help
>> help sqrt

9. Once a command has been entered and executed, it can be recalled, edited if necessary and executed again by using the arrow cursor keys. Enter the following command:

>> C = [1 2 3; 5 6 7 ]

Then use the up arrow key to recall the command and edit it with the cursor keys to add a 4 to the end of the first row and an 8 to the end of the second row of C:

>> C = [1 2 3 4; 5 6 7 8 ]

You can also select commands from the History window to reexecute.

help cedit provides some additional information on editing.

10. MATLAB has a rich set of mathematical functions available and also provides the ability for the user to define new functions for subsequent use.


>> y = log(x)
>> r = x*cos(pi/6)

11.  All the variables that you have created and their current values are saved in memory (in an area called the workspace).   You can view your workspace in a Window by choosing workspace from the pull-down Window menu. 


Once you exit MATLAB all values of the variables are lost.  If you want to save them choose the save button in the Workspace Window.

This saves the variables and their values in a file call filename.mat.   Try this by saving your variables in a file called NumAnal1.

 

When you want to load the variable values form the file use the Import Data button in the Workspace Window.  (Try this for the NumAnal1 file).

 

12.  If you want to clear a variable from workspace,  click on the variable in the Workspace window and then choose the Delete button.  Try this for the variable C.

13. The symbolic toolbox in MATLAB allows one to run the Maple kernel to do symbolic computations that MATLAB itself does not provide for.   The syntax is

maple ('exact-maple-command')

For example to compute the symbolic antiderivative of sin(x)

>>
maple('int(sin(x),x)')

14.  Testing the limits of MATLAB accuracy.  Enter the following to determine what the commands eps, realmax, and realmin tell us about the limited precision of MATLAB's floating point numbers.

>> help eps
>> eps
>> help realmax
>> realmax
>> help realmin

>> realmin
>> 0/0   
>> help NaN
>> 1/0   

>> help inf

15.  To observe the potential difficulties in round-off error caused by limited precision of floating point numbers enter the following commands to compute some simple sums.  What happens?

>> format long e
>> 3 + .2 

>> ans + .2
>> ans + .2

 


M-Files:  Scripts and Functions

An m-file is a text file that contains either a sequence of MATLAB commands (in which case it is called a script file) or a definition of a MATLAB function (in which case it is called a function file).

Script Files
A script file is an ordinary text file that contains a sequence of MATLAB commands. When invoked in MATLAB, the sequence of commands in the script file is executed, in order, just as if the user were entering them interactively at the command prompt.

To create a script file, open the MATLAB debugger-editor by choosing File-New-M-file   If you want to  insert comments into the file, you must use a % symbol at the beginning of each line of the  comment. Otherwise you type MATLAB commands as you would in the MATLAB  window.

1.  Create a script file called squares.m that calculates the squares of the integers from 1 to 10.  Choose File-New-M-File and enter the code below. Then choose File-Save and save in your N:\m439 directory as squares.m.

%SQUARES -- calculates the squares of the integers from 1 to 10
square = [ ];
i = 1;
while i <= 10
   square(i) = i^2
   i = i + 1;  
end

2.  Invoke this file in MATLAB, you would simply type:

 >> squares

Note that this just executes the commands in the script file

Function Files
Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and the name of the function should be the same. Functions operate on variables within their own local workspace, separate from the workspace you access at the MATLAB command prompt.

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments.
function output-argument = name-of-function (input-arguments)

3.  Create an  m-file called  g.m  in your N:\m439 directory containing the following:

function y = g(x)
% g:  Defines the function y = g(x) below
%  x is a real number
y = 1 + x - x.^2 ./4;

Note in the above file the use of the operators .^  and ./  for exponentiation and division.  We also use ‘.*’ for ordinary multiplication.  This is used to avoid conflict with the matrix multiplication and related operations for matrices. 

4.  Call the function g using the following commands:
>>  g(2)
>>  result = g(4)


Finding Zeros of Functions

Our next topic in this course will be  the investigation of several different methods for finding zeros of functions (i.e. x is a zero of the function f if f(x) =0).

Execute the commands below to graph g on the specified range.
>> clf
>> fplot('g',[-2.5 2.5])

From the plot we can see there is a zero for the function in this range.   We could easily compute the two roots of the above function g by using the quadratic formula.  This however is not the case for most functions.   The built-in command fzero in MATLAB uses a numerical method to find an approximation to a zero of a function near a specified value.   This command combines the best features of some of the methods we will investigate.

 We ask MATLAB to find a zero near the point  -1 with the following command

>> fzero('g',-1)

Note that the answer is returned in scientific notation and indicates a root of approximately -0.82842746…

ans =

 

   -8.284271247461901e-001