LEARNING   MATLAB       Contra Costa College MatLab Stuff         Math Dept. Home Page   
    Getting Started     First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6      

Learning Matlab

A Tutorial for Getting Started in MatLab
by Thomas M. Green

Contra Costa College

Natural & Applied Sciences Division (NAS)
Mathematics Department

L-Wave Matlab is a computer program for doing numerical computation. It began as a "MATrix LABoratory" program in the late 1970s, intended to provide interactive access to the FORTRAN libraries Linpack and Eispack. These are carefully tested, high-quality programming packages for solving linear equations and eigenvalue problems. The goal of MatLab is to enable scientists to use matrix-based techniques to solve problems, using state-of-the-art code, without having to write programs in traditional languages like C and Fortran. More capabilities have been added as time has passed -- many more commands, a programming environment, and very fine graphics capabilities.

Matlab is available from The MathWorks, Inc.
Natick, MA. Information can be found at
"http://www.mathworks.com".
LOGO

The following sessions will introduce you to MatLab and how you can use it to do calculations, solve problems, create plots and write your own functions. Use each session as a guided tour as you work through the examples presented therein while using MatLab. These sessions are designed to introduce the features of MatLab to a Pre-Calculus student so that MatLab can be used in the study of the Calculus and higher mathematics.

Note:
(Also, we offer a short-term, 6 week course,
Math 175 - Intro. to MatLab, beginning in the Fall '98 semester and
in subsequent semesters covering this material essentially
at the pre-calculus level.)
Look at
button key
Outline


   (If you are viewing a printed copy of this document, then be advised that
   these sessions are available on-line over the Internet.  When one visits
   the Contra Costa College Home Page (www.contracosta.edu), it's found
   via a link from the the Math Dept. Home Page. )

Sessions:


This document last modified: May 15, 2004.
By Thomas M. Green
Contra Costa College
San Pablo, CA 94806
Permission to use this document is granted so long as
the author is acknowledged.
Please send comments and suggestions to:
Thomas M. Green c/o CCC Math Dept. hwalters@contracosta.edu


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 


First Session

 ________________________________

MatLab Demos

MatLab Commands, Functions, Operations covered in this Session:
COMMANDS:
helpwin
helpdesk
demo
quit

Note:
In these sessions, rather than continually switching back and forth between this window and MatLab's window, it might be easier to print these sessions and use the printout to follow along while working in MatLab.

MatLab is installed in the NAS Computer Lab, or check with the Natural and Applied Science Division.

To start the program choose Math and then MatLab from the Start menu of Windows 95. The system should respond with the MatLab logo and then with the MatLab workspace as follows:

      This version is for educational classroom use only.

      To get started, type one of these commands: helpwin, helpdesk, or demo

      >> 

The ">>" is Matlab's prompt. You type your commands for MatLab following this prompt. To quit MatLab type quit at the prompt.
      >> quit

Before we quit, however, our first session will be to explore some demos to see examples of MatLab at work. Type:

	>> demo
The MatLab Demos window will display three dialog boxes and two buttons. (You may want to expand the window to the full screen.) In the first box select the Visualization option. Read the text in the second box. In the third box select the 2-D Plots option, then click the Run the "Demo" button. Follow the directions in the MiniCommand window that appears.

Close the demo and select Klein Bottle Example from the third box for your next demo. Check out the Info button before closing this demo.

Next try the Vibration Movie.

Now, back at the MatLab Demos window select Gallery in the first box. Again read the second box and then select Knot in the third box and click the Run the "Demo button. Close that and try another selection or two before proceeding.

Back at the MatLab Demos window select Games in the first box. Again read the second box and then select one of the game demos in the third box and try it out.

Next, select Numerics in the first box of the MatLab Demos window, read the second box, and select 2-D Visual Solutions in the third box. Now click the Run the "Demo" button.
After viewing the demo, answer the following question?
Which is larger, e^pi or pi^e ?

Which is larger, e^pi or pi^e ? Ans. __________
		Write your answer on the printed copy.

Close the demo, close the MatLab Demos window, and enter the "quit" command at the prompt to terminate this MatLab session.

Finally, during the next week visit the MathWorks website several times for more information.
Matlab is available from The MathWorks, Inc. Natick, MA. Information can be found at "http://www.mathworks.com".

					  End of Session 1.


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 


Session 2

 ________________________________

Arithmetic Calculator

MatLab Commands, Functions, Operations covered in this Session:
COMMANDS:
diary
who
save
load
help
dir
format
what
edit
FUNCTIONS:
sqrt
OPERATIONS:
See
Table
Below

Some of the MatLab operations use fairly standard notation.

Some MatLab Operations

Symbol Name Example
+ Plus 2 + 3
- Minus 2 - 4
* Multiply 2*3
/ Division (Right) 2/3
\ Division (Left) 2\3
^ Power 2^4
( ) Parentheses (Precedence) 2*(3 + 4)
( ) Parentheses (Function) cos(x)
= Assignment x = 2
== Equality x == X
Powers are accomplished using the ^ symbol. 4^3 is the same as 43.

If you have the Student Edition of MatLab or your own copy, you can make a record of your sessions. The "diary" command saves your work in a file named "session2" as shown below: Type:

	>> diary session2
To stop recording the session, use
	>> diary off
More than one command may be entered on a single line, if they are seperated by commas. Type in each expression:
	>> 2+3
	>> 3*4, 2-4
As is the convention, powers are performed before division and multiplication, which are done before subtraction and addition.
	>> 2+3*4^2
The arrow keys up down left right allow "command-line editing," which cuts down on the amount of typing required, and allows easy error correction. Press the "up" arrow, and add "/5." What will this produce?
	>> 2+3*4^2/5
Note:
Repeated pressing of the up arrow key scrolls back through prior commands. Similarly, pressing the down arrow key scrolls forward through the commands. At any time pressing the left right arrow keys moves the cursor within the current command at the prompt.
To correct an error in a previous command, use the arrow keys to place the cursor at the proper location, press "Delete" to remove a character, or enter a character to insert it, or both if necessary. Press "Enter" to tell MatLab to reevaluate the expression.

Parentheses may be used to group terms, or to make them more readable.

	>> (2 + 3*4^2)/5

Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB uses only the first 31 characters of a variable name. Names are case sensitive; MatLab distinguishes between uppercase and lowercase letters. A and a are not the same variable.

The "=" sign is used to assign values to variables and the "==" sign is used to compare variables.

	>> x = 4
	>> y = x^3
	>> y/x
	>> X = 1;
	>> X == x
	>> Area = x*y
(A semicolon placed at the end of a MatLab statement suppresses the printing of the results.)

If no other name is given, an answer is saved in a variable named ans.

	>> 4 + 6
	>> ans, z=ans^2, ans 
Here z was defined in terms of ans. The result was called z, so ans was unchanged.

To get a list of your variables, use

	>> who
To evaluate your variables, just enter their names.
	>> x, y, ans, X, Area
Note:
  • More than one command may be entered on a single line, if they are seperated by commas.
  • Names are case sensitive; MatLab distinguishes between uppercase and lowercase letters.
  • A semicolon placed at the end of a MatLab statement suppresses the printing of the results.
  • If no other name is given, an answer is saved in a variable named ans.

To save your workspace variables you can use the save command. This will save all workspace variables in a file named matlab.mat. The data can be retrieved with the load command.
(These commands are also available as options in the MatLab File menu.)
To save all workspace variables in a file named myvars.mat, in reloadable format, use
	>> save myvars
To restore the workspace, use
	>> load myvars
There are other variations of the save command and you can either look these up in the text, the reference manuals, use the help save command, or use the helpdesk command. There's also a "lookfor" command, so that you don't have to guess the topic name precisely (more on this in Session 3).
	>> help
	>> help save
	>> help sqrt
	>> helpdesk
	>> dir

All arithmetic is done to double precision [about 16 decimal digits], even though results are normally displayed in a shorter form. MATLAB uses conventional decimal notation for numbers, with an optional decimal point and leading plus or minus sign. Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of legal numbers are

All numbers are stored internally using the long format specified by the IEEE floating-point standard. Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 10-308 to 10+308.

	>> -4e3
	>> a=sqrt(2)
	>> format long, b=sqrt(2)
	>> a-b
	>> 10/30, format rat, 10/30
	>> format short
	>> ans

Suppose we want to solve the quadratic equation ax2 + bx + c = 0. (In Session 4 we will learn about a special built-in function called roots for solving polynomial equations in general. For now we will use the quadratic formula.) The roots are given by

       x1 = (-b + sqrt(b2 - 4ac))/(2a)
     and
       x2 = (-b - sqrt(b2 - 4ac))/(2a)
In MatLab we type:
	>> a=1, b=8, c=12       %set the coeficients to 1, 8, and 12
        >> x1 = (-b + sqrt(b^2 - 4*a*c))/(2*a)
        >> x2 = (-b - sqrt(b^2 - 4*a*c))/(2*a)
	>> a*x1^2+b*x1+c   %substitute x1 to check answer
	>> a*x2^2+b*x2+c   %substitute x2 to check answer
				 %What should ans equal now? 

x1 = Ans. __________
x2 = Ans. __________
ans = Ans. __________
		Write your answers on the printed copy.

Matlab statements, like the above, can be prepared with any editor, and stored in a file for later use. The file is referred to as a script, or an M-File (since they must have names of the form filename.m). We can also use the MatLab special editor. From the File menu choose New and select M-File.
This brings up the text editor window where we can enter our statements. Save the file with the extension .m, for example, quadrat.m. Then in the MatLab workspace just enter the prefix file name to have MatLab load and execute the statements.

	>> quadrat
This approach is convenient for longer sequences of statements or when data is entered into large arrays or matrices. The files can be re-edited to make changes if desired, and then re-executed. The what command returns a listing of all M-Files in the current directory or folder:
	>> what
The command edit calls up the special editor, so changes can be made if necessary:
	>> edit quadrat.m

Finally, to stop a Matlab session and return to the operating system, use

	>> quit

					  End of Session 2.


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 



Session 3

 ________________________________

Built-In Functions

MatLab Commands, Functions, Operations covered in this Session:
COMMANDS:
lookfor
help
format
clear
FUNCTIONS:
sqrt
round
ceil
floor
real
imag
conj
abs
 
exp
log
log10
cosh
acosh
sin
cos
tan
asin
fzero
fmin
CONSTANTS:
realmax
realmin
pi
i, j
eps
inf
nan

MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin.

Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically.

	>> a=sqrt(-1)
	>> b=sqrt(a)
	>> c=b^2
	>> b/a
	>> b\a
	>> a/b
In MatLab no special handling of complex numbers is required. Operations on complex numbers are written the same as for real numbers and the results are handled by MatLab automatically.
Solve the following quadratic equation ax2 + bx + c = 0 if a, b, and c each equal 1.

	>> a=1, b=1, c=1
        >> x1 = (-b + sqrt(b^2 - 4*a*c))/(2*a)
        >> x2 = (-b - sqrt(b^2 - 4*a*c))/(2*a)
	>> a*x1^2+b*x1+c   %substitute x1 to check answer
	>> a*x2^2+b*x2+c   %substitute x2 to check answer
				 %What should ans equal now? 

x1 = Ans. __________
x2 = Ans. __________
ans = Ans. __________
		Write your answers on the printed copy.

MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments. For a list of the elementary mathematical functions, type

	>> help elfun
Some of the functions, like sqrt and sin, are built-in. They are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in M-files (We'll examine M-files further in Session 4). You can see the code and even modify it if you want.

Try the following to determine the effect of the functions round, ceil and floor.

	>> a=sqrt(2)
	>> b=sqrt(3)
	>> round(a), round(b)
	>> ceil(a), ceil(b)
	>> floor(a), floor(b)
a = __________ round(a) = __________
ceil(a) = __________
floor(a) = __________
b = __________ round(a) = __________
ceil(a) = __________
floor(a) = __________
		Write your answers on the printed copy.


Several special functions provide values of useful constants.
pi     3.14159265
i     imaginary unit, -1
j     same as i
eps     floating-point relative precision, 2-52
realmin   smallest floating-point number, 2-1022
realmax   largest floating-point number, (2-)21023
inf infinity
nan Not-a-number

Type the following and take note of each result:

	>> a=1+3i
	>> b=4-3i
	>> c=a + b
	>> d=a*b
	>> b\a
	>> a/b
	>> i
	>> i == sqrt(-1)
The lookfor command provides help by searching for a keyword (not necessarily a command). It returns those first lines of the MatLab help topics containing your keyword. Try the following:
	>> lookfor complex
and then try:
        >> b=4-3i
	>> b, real(b), imag(b)
	>> conj(b)
	>> abs(b)
Try the following (and record your results on the printed copy):
        >> format long, pi      _____________________________________

        >> realmax              _____________________________________

        >> realmin              _____________________________________

        >> format rat, pi       _____________________________________

        >> 2*pi                 _____________________________________

        >> format short         _____________________________________

        >> pi                   _____________________________________

        >> 0/3                  _____________________________________

        >> 3/0                  _____________________________________

        >> 1 + realmax          _____________________________________

        >> ans + ans            _____________________________________

        >> 0/0                  _____________________________________ 

Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined mathematical expressions that overflow, i.e., exceed realmax. Not-a-number is generated by trying to evaluate expressions like 0/0 or inf-inf that do not have well defined mathematical values.
Note: The function names are not reserved. It is possible to overwrite any of them with a new variable, such as

and then use that value in subsequent calculations. The original function can be restored with

Try the following exponential and logarithmic function expressions:

	>> log(1), log(10), log(100), log(1000)
	>> log10(1), log10(10), log10(100), log10(1000)
	>> log(0), log10(0)
        >> exp(-1), exp(0), exp(1) ____________________________________

        >> exp(-1), 1/exp(1)       ____________________________________
	>> 10^log10(100)
	>> exp(log(10)), log(exp(10))
	>> x = 2.345, (exp(x)+exp(-x))/2, cosh(x)
	>> acosh(x), cosh(acosh(x))
        >> realmax, log10(realmax) ____________________________________
What is the value of exp(1)? Ans. __________
		Write your answer on the printed copy.

The value of exp(1) is the base of the natural logarithmic and exponential functions. It is usually represented in mathematics by the symbol e.
	>> e = exp(1)
	>> e^pi
	>> pi^e

Which is larger, e^pi or pi^e ? Ans. __________
           Write your answer on the printed copy.

The trigonometric functions work in radian angle measure.

	    180 degrees = pi radians, 
Type in the following:
	>> sin(pi), cos(pi), tan(pi) 
	>> sin(pi/2), cos(pi/2), tan(pi/2)
	>> sin(pi/4), cos(pi/4), tan(pi/4)
	>> pi/4, asin(sin(pi/4))
and then these (and record your results on the printed copy):
        >> x = sqrt(2)/2      ____________________________________

        >> y = asin(x)        ____________________________________

        >> y_deg = y*180/pi   ____________________________________
Finally,
	>> sin(pi/2), sqrt(4)/2
	>> sin(pi/3), sqrt(3)/2
	>> sin(pi/4), sqrt(2)/2
	>> sin(pi/6), sqrt(1)/2
Examine the last four results and draw a conclusion from what you observe. In standard mathematical notation write your conclusions in the table below:


_________________________________

_________________________________

_________________________________

_________________________________
		Write your answers on the printed copy.

MatLab also provides a set of function functions. By that, we mean functions that work with arguments which are themselves functions. As an example, we will examine the function fzero:

	>> x = fzero( 'sin', 3)
This returns the value of pi since the sine of pi is zero. The function fzero takes two arguments, the first is the name of the function presented as a string in single quotes, the second is an arbitrary value chosen near the value of the "zero of the function". The function fzero will use numerical methods to try to find the point where the input function crosses the x-axis closest to the input value. For functions with no valid zeros, fzero may execute until you terminate it (with control-C) or return an erroneous result. Try the following (and record your results on the printed copy):
        >> fzero( 'log', 3)   ____________________________________

        >> fzero( 'exp', -1)  ____________________________________

        >> fzero( 'sqrt', 1)  ____________________________________

        >> fzero( 'tan', 3)   ____________________________________
A limitation of fzero is that zeros of functions that touch, but do not cross the x-axis are not found by fzero since it's looking for a sign change in the evaluation of the input function. For polynomial functions we can use another function called roots that works for polynomials. We will cover polynomials in the next session.

Another function function is fmin which returns one of the x-values in the domain specified where the minimum value of the input function can be found. The next example finds the x-value where the sine function has a minimum value over the interval from 0 to 2*pi.

	>> x = fmin( 'sin', 0, 2*pi)
What did you find? ____________________________________ Then to get the minimum value of the function we need:
        >> y_min = sin(x)
					  End of Session 3.


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 



Session 4

 ________________________________

Polynomials, User Functions, M-Files

MatLab Commands, Functions, Operations covered in this Session:
COMMANDS:
function
(function functions)
(M-files)
FUNCTIONS:
roots
poly
real
polyval
linspace
conv
deconv
 
function
prod
OPERATORS:
    :
.*
./
.\
.^
.'
[ ]


Polynomials & Vectors

Interestingly, in MatLab a polynomial is represented by a vector! The elements of the vector are the coefficients of the polynomial in descending order.
For example, the polynomial x2 + 8x + 12 is entered as

	>> p = [1 8 12]
The polynomial x4 - 12x3 + 25x + 116 is entered as
	>> q = [1 -12 0 25 116]
Note:
  • Vectors in MatLab are arrays (ordered lists) of elements, numbers in this case.
  • The elements are separated from one another by a space (or spaces) and not commas.
  • The elements are enclosed in brackets, [ ]. (The same is true of matrices in MatLab, but matrices will be discussed at another time.)
  • Terms with zero coefficents must be included.

One of the most useful functions for polynomials, and a very powerful function, is roots for finding the roots of a polynomial.

	>> roots_of_p = roots(p)
	>> roots_of_q = roots(q)
The roots of a polynomial also form a vector in MatLab. This vector, however, is organized as a column vector, as opposed to the polynomial vector representation which is organized as a row vector. Thus, in MatLab you will see a column display of the roots.

Given the roots of a polynomial, it is also possible to construct the associated polynomial by using the poly function.

	>> original_p = poly(roots_of_p)
	>> original_q = poly(roots_of_q)
Occasionally, when complex roots are involved, you may get complex forms for the coefficients. If the imaginary parts of these expressions are zeros, they can be discarded as follows:
	>> original_p = real(original_p)  %discard imag. part
	>> original_q = real(original_q)

A polynomial can be evaluated at a value of the independent variable using polyval. The polynomial p, given above for instance would be evaluated at, say -6, one of its roots, as follows:

	>> value_of_p = polyval( p, -6)
(Of course, if -6 is a root, the value of p should be ____________) Try the following:
	>> value_of_q = polyval( q, -1-i)
	>> value_of_q = polyval( q, [2 3])
Here, we see that a polynomial can be evaluated at complex values and if the the second argument is a vector, then the polynomial is evaluated at each of the elements, and value_of_q is itself a vector in the latter case.
Also, in this example, the values of q at 2 and at 3 are of opposite sign implying that one of the roots of q is between 2 and 3. Check it out.

The function polyval is similar to a function function (Session 3), however, the arguments for polyval are two vectors. Most of MatLab's utility is based on using vectors or matrices for input and output, making it a very powerful mathematical tool. The built-in elementary functions, for instance, all accept a vector input. Try the following:

	>> x = [ 0 pi/6 pi/4 pi/3 pi/2 ] ;
	>> y = sin(x)

The colon operator,:, in MatLab is used to create vectors. The expression 1:10 is the same as [1 2 3 4 5 6 7 8 9 10]. Suppose we wanted to evaluate the polynomial q over the integers from -5 to 5. In MatLab enter the following:

	>> vector = -5:5
	>> value_of_q = polyval( q, vector)
In this example, by viewing ans we can determine that q is a decreasing function over the interval from -5 to 5.
To create a vector with arbitrary real increments MatLab provides a two colon operator as follows:
	>> vector = -5:0.1:5
	>> value_of_q = polyval( q, vector)
This time q is evaluated at over one hundred values from -5 to 5, incrementing the independent variable by 0.1.
If we wanted to evaluate q at exactly 100 points (values) we would use MatLab's linspace function.
linspace(-5, 5, 100) generates 100 evenly spaced points starting with -5 and ending with 5. The space between points (or increment) is controlled by MatLab.
	>> vector = linspace(-5, 5, 100) ;  %100 points between -5 and 5
	>> value_of_q = polyval( q, vector)

In MatLab the multiplication of two polynomials is accomplished by the convolution of two arrays. The conv function is used and takes two arguments, the polynomials to be multiplied. For example, to multiply the polynomial x2 + 8x + 12 and the polynomial x4 - 12x3 + 25x + 116 enter the following:

	>> p = [1 8 12]; q = [1 -12 0 25 116] ;
	>> product = conv(p, q)
In this example, the degree of the product is 6, which can also be determined by counting the terms in ans (starting at zero). Multiplying more than two polynomials requires repeated use of conv.
Using conv find the following powers of x + 1:

(x + 1)^2

_________________________________

(x + 1)^3

_________________________________

(x + 1)^4

_________________________________

(x + 1)^5

_________________________________
		Write your answers on the printed copy.

Division is accomplished with the function deconv which also takes two arguments, but this time the order of the arguments matters. The first argument is the dividend and the second is the divisor. Also, not all divisions come out exact, there can be a nonzero remainder. The following examples will illustrate this (using p and q from above):

	>> [quot, remain] = deconv(q, p)   %dividing q by p
	>> [quot, remain] = deconv(p, q)   %dividing p by q

Note that the results, quotient and remainder are collected in an array of two vectors, each representing a polynomial. Consider this, what are the degrees of the quotient and remainder in the two examples above?

There are no functions in MatLab to add or subtract polynomials. However, polynomials are represented by vectors and these can be added, subtracted and multiplied by a scalar if desired. The difference is that vectors must be of the same size in order to be added or subtracted. Thus, if v1 = [1 2 3] and v2 = [3 -4 5], then

	>> v1=[1 2 3]; v2=[3 -4 5]; 
	>> Sum=v1 + v2
This works out ok. But that being the case, how would you add p and q from the above examples? Write the MatLab statements to add p and q in the boxes below:
(Hint: Sum = p + q won't work unless you redefine p.)

p =

_________________________________

q =

_________________________________
Sum =
_________________________________
		Write your answers on the printed copy.

Note:
Although there are no functions in basic MatLab to add or subtract polynomials, there are tools in the Symbolic Math Toolbox (another MathWorks product) to enter symbolic expressions, symbolic equations, etc., and to carry out all of the fundamental algebraic operations (including addition and subtraction, and solving equations symbolically), as well as those processes and operations of the calculus, linear algebra, differential equations, and more. The handling of symbolic expressions, which are character strings or arrays of character strings, is the topic of another set of tutorial lessons.


User Functions and M-Files

We will use the factorial function as an example of a user-defined function.

	function f = fact(n)
	%FACT Factorial
	%FACT(n) returns the factorial of n, denoted n!
	%The built-in function, prod, is used because
	%FACT(n) = prod(1:n).  See Also: prod

	f = prod(1:n) ;  %uses the colon : operator
This function has some elements common to all MatLab functions:
Note:
  • Line 1: A function definition or header line. This line defines the function name and the number and order of the input and output argumnents.
  • Line 2: A H1 line. H1 stands for "help 1" line. This line is used by the online MatLab help system when help or lookfor command are invoked. Line 2 starts with a % symbol indicating that this line is a comment, not an executable statement.
  • Lines 3-5: Additional comments providing more of the "help" text, all beginning with the % symbol.
  • Last Line(s): A function body. May consist of many lines. This part of the function contains the statements to perform the computations and assign values to any output arguments.

The function definition line, function f = fact(n), has five parts:

  1. the keyword, function.
  2. the output argument, f.
  3. the equal sign, =.
  4. the function name, fact.
  5. the input argument, n.

There can be more than one input argument as well as more than one output argument. For example,
        function [x,y] = polarconv(r, theta)
Use brackets for the output arguments and separate the arguments with commas.

Now that we have seen a MatLab function, we need to put it in action. User defined functions, such as the example above, are placed in special MatLab files called M-Files. These files can be created using a text editor or the MatLab special editor, just as was the case with MatLab scripts discussed in Session 2.
From the File menu choose New and select M-File. This brings up the text editor window where we can enter our functions. When the file is saved it should be saved with a filename the same as the function name, followed by .m . In the example above, the fact function we would type in each of the lines indicated, including the comment lines, and then save the file with the name fact.m .

We can then use the function in the MatLab workspace as follows:

	>> a = fact(10) 
	>> x = 14
	>> y = fact(x)
	>> z = fact(x)/(fact(10)*fact(x - 10))
That is, fact is used just like any other MatLab function might be used.
(Note, mathematically, the value of z given should be the number of differnent groups of 10 one could select from a collection of 14 objects.)

Create the function y = f(x) where f(x) = x2 - 1/x and evaluate the function at x equal to the values -1, -0.5, 0, 0.5, and 1. (The function should be undefined at x = 0.)

Now create the same function, f(x), so that it will accept a vector input. In order to do this we need to learn more about vector operations.

MatLab Array Operations
Assume U and V are vectors of the same size and s is a scalar.
Symbol Name Example
+ Scalar Addition V + s
* Scalar Multiplication s*V
./ Scalar Divided by Array s./V
+ Array Addition U + V
.* Array Multiplication(Right) U.*V
./ Array Division (Right) U./V
.\ Array Division (Left) U.\V
.^ Array Power (Scalar Exponent) V.^s
.^ Array Power (Scalar Base) s.^V
.^ Array Power (Array to Array) U.^V
.' Transpose V.'
[] Array [-5:5]
Try the following:
	>> s = 3 
	>> U = 1:4
	>> V = [5 10 15 20]
	>> V + s
	>> s*V 
	>> U + V         % U - V also works
	>> U.*V
	>> U./V
	>> U.\V
	>> V.^s
	>> s.^V
	>> V.^U
	>> V.'
Now to create the function, f(x), so that it will accept a vector input, we just need to change the operations to the appropriate array operations. For example, change x^2 to x.^2 and 1/x to 1./x.
Use this new version of f(x) to evaluate it at x = [-1:0.5:1] and then find its zero(s) with fzero (see Session 3).

New functions can be created in terms of existing functions in MatLab. For additional practice, create a function called, cat that takes one input argument, x, and returns a value equal to

	(exp(x) + exp(-x))/2
Use the cat function to find the values of cat(-2) through cat(2). Then find the values of the built-in cosh function over the same domain. What did you discover?
Try the function function fmin on the cat function. (See Session 3)

The expression

	fact(n)/(fact(r)*fact(n-r))
is called a combinatorial or a binomial coefficient (with r less than or equal to n). In the case of the binomial coeficient, it is returned by this expression as the coefficent of the term involving xr when the binomial, (x + 1), is raised to the nth power and expanded.
Write a function called comb that will return the value of this expression when called with two input arguments, n and r.
Use this function to find the values of
	comb(4,4), comb(4,3), comb(4,2), comb(4,1), comb(4,0)
Compare your results to the 4th row of Pascal's Triangle.

Note:
MatLab also provides the common programming constructs, such as, logical operators, if_then_else decision making, for_ loops, and while_ loops. These can be used in creating your own functions or directly in the MatLab workspace. Here is an example, creating a "program loop."
	>> total=0 ;
	>> for i=1:100 
	>>       total = total + i ;
	>> end
	>> total
However, these are topics for another tutorial session.

					  End of Session 4.


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 



Session 5

 ________________________________

Graphics, 2-D Plots

MatLab Commands, Functions, Operations covered in this Session:
COMMANDS:
figure
grid
hold
gtext
orient
print
clf
zoom
axis
gcf
pause
FUNCTIONS:
linspace
plot
figure
axis
title
xlabel
ylabel
 
text
polar
cart2pol
pol2cart
fplot
subplot
fill


The graphics capabilites of MatLab are extensive, including both 2 and 3 dimensional plots. Begin by trying the following:

	>> x = linspace(-pi, pi, 40) ;
	>> y = sin(x) ; 
	>> plot(x, y)
Press the enter key
to return from the figure
window to the MatLab workspace.

The graph was generated by MatLab as a plot of y vs. x ( both x and y are vectors (arrays)) by placing 40 points in the figure window and connecting them by straight lines. In this example x is a vector of 40 entries evenly positioned between -pi and pi. The plot function can take two or more arguments, the first two of which are vectors. (plot can also take just one vector argument, see the online help system for more information.)
The following generates a graph of x vs. y and adds a grid system:

	>> plot(y, x)
	>> grid
	>> figure(1)
The grid system is a feature of the current plot. Just entering the grid command toggles the grid from 'off' to 'on' or 'on' to 'off' (if it was already on) in the current figure window. We can also turn it on or off with the commands >> grid on or
>> grid off.
Other features include axis and graph annotations, such as, labels, legend, and text. We will demonstrate these in the upcoming examples.

After our first plot, we need to recall the figure window with figure(1).
MatLab directs all graphics output to a figure window. When we add a feature, we can redisplay the figure window in several ways, one of which is to type the statement

	>> figure(1)
We may have several figure windows available in any given session, and the figure function returns the selected figure window to view.
The other way to view a figure window is to 'click' on its icon in the status bar at the bottom of the workspace window, or the 'Window' pull-down menu from the menu bar near the top of the workspace window.
figure by itself opens a new figure window:
	>> figure
The command gcf gets the current figure window handle. We will use this frequently in our graphic scripts. There are many more properties for the figure function that we won't go into here. Also the set function can specify properties, such as, background colors, axes colors, window resizing, and more. See the online help system for more information.

When we generate a new plot, the old plot is cleared unless one of the following conditions hold:


In the first case we end up with two figure windows; in the second case we have only one figure window and subsequent plots (using hold) and features are added to that figure window.
The following plots y vs. x and x vs. y in the same figure window:
	>> plot(x, y)
	>> hold on
	>> plot(y, x)
	>> hold off
        >> figure(gcf)
We can get the same result with the 'extended' plot function:
	>> plot(x, y, y, x)
	>> figure(1)
Here two plots, y vs. x and x vs. y are created in the same figure.

Sometimes we just want to start over with a figure window. Use the command clf to clear the current figure window.

After we generate a plot, we add features, such as demonstrated in the following: (this is a good place to create a script m-file!)

        >> clf
	>> x = linspace(0, 4*pi, 50);
	>> y = 1.5*sin(x-1) ;
	>> plot(x, y)
	>> grid
	>> axis([0,15,-2,2])
	>> title('Harmonic Motion')
	>> xlabel('Time in Seconds')
	>> ylabel('Displacement in Feet')
	>> text(3*pi/4+1, sin(3*pi/4), '\leftarrowdescending')
        >> figure(gcf)
There are several features added to the figure window in the example above: grid, axis, title, xlabel, ylabel, and text.
The axis function sets the scaling for the x- and y-axis on the current plot, overriding MatLab's automatic scaling.
The general form is axis([ xmin, xmax, ymin, ymax ]). To make the x- and y-axis data units to be equal, use axis equal or axis equal tight. The latter form causes the axes shape to conform to the plotted data. We can return to automatic scaling with
	>> axis auto
	>> figure(1)
Here, axis is used more like a command than a function with auto as a parameter, however, in MatLab commands and functions are interchangeable to a certain extent. For instance, the command given above could be written axis( 'auto' ). The parameter 'auto' is now the argument of the function expressed as a string. There are many more properties for the axis function that we won't go into here. See the online help system for more information.
The function text(x,y,S) adds the character string S to the current plot at the coordinates (x,y).
Another command, gtext lets you place text on your plot interactively using the mouse.

The plot function also has an optional string argument, called linetype, where we can specify color, linestyle, and marker for the given plot. For example:

	>> plot(x, y, 'red : pentagram')
        >> figure(gcf)
plots a red dotted line marked off at each point of the vectors x & y with a five point star symbol (pentagram). Without this string argument the default linetype is a solid line without markers and in the MatLab automatic color choice.

LineType Symbols
Symbol Color
c cyan
m magenta
y yellow
r red
g green
b blue
w white
k black
Symbol Line Style
- solid (default)
-- dashed
: dotted
-. dash-dot
none no line
Symbol Marker Description
+ plus signs
o circle
* asterisk
. point
x cross
square square
^ upward pointing triangle
v downward pointing triangle
> right pointing triangle
< left pointing triangle
pentagram five-pointed star
hexagram six-pointed star
none no marker (default)

The following code plots the sine function twice, once with the default linetype built into MatLab, the second with the data points marked with green asterisks :

        >> clf
	>> x = linspace(0, 2*pi, 30) ;
	>> y = sin(x) ;
        >> plot(x, y, x, y, 'g *')
        >> figure(gcf)
In general, the plot function can take multiple sets of triples of arguments like this:
	>> plot( x1, y1, 'linetype1', x2, y2, 'linetype2', ... )
where the x's and y's are vectors and the linetypes are strings containing up to three designators: color, line style, and/or marker.

The print command sends the contents of the current figure window to the default printer. We can either orient the output in landscape or portrait mode.

        >> clf
	>> x = 0:0.05:2*pi ;
	>> y = 3*sin(x./2) ;
	>> plot(x, y)
        >> figure(gcf)
	>> orient landscape
	>> print
There are other options for the print command. See the online help system for more information.

We can interactively zoom in or out at various points of a 2-D plot in order to view a specific region in more detail. The command zoom on turns on the zoom mode and zoom off turns it off. While in zoom mode we are prompted for the zoom center with the mouse. We can zoom in by pressing the left mouse button and zoom out by pressing the right mouse button. The command zoom out zooms out fully, and just using the command zoom toggles the zoom mode.

We can also create polar coordinate plots where the independent variable, t in the following example, is measured in radians:

        >> clf
	>> t = 0:0.05:2*pi ;
	>> r = sin(2*t) ;
	>> polar(t, r, 'red')
        >> figure(gcf)
Data stored in Cartesian coordinates can easily be converted to polar coordinates by using the cart2pol function and back again using the pol2cart function. Here is an example:
        >> clf
	>> t = 0:0.05:2*pi ;
	>> x = 5*sin(t) ;
	>> y = 5*cos(t) ;
	>> plot(x, y), title('Cartesian')
        >> figure(gcf)
        >> pause
	>> figure
	>> [theta rho] = cart2pol(x, y) ;
	>> polar(theta, rho), title('Polar')
        >> figure(gcf)
Here we created two different figure windows. The pause command suspends execution until a key is pressed. Like plot, the cart2pol function takes two vector arguments representing the abscissae and ordinates of points determined to be Cartesian, but cart2pol returns two column vectors representing the corresponding polar coordinates which can then be plotted using polar.
The function pol2cart works in a similar manner to reverse the process.

The preceding example also illustrates the plotting of parametric equations, with the parameter being t in this case for plotting xy coordinates for a circle. Using parametric equations, we can plot many possibilities. Here is an example of an ellipse:

        >> clf
	>> t = 0:0.05:2*pi ;
	>> x = 3*sin(t) ;
	>> y = 5*cos(t) ;
	>> plot(x, y), title('Ellipse')
        >> figure(gcf)

Similar to parametric equations, we can also plot various polygons. Here is an example of a pentagon (5 vertices):

        >> clf
        >> t = linspace(0, 2*pi, 6) ;
	>> x = sin(t) ;
	>> y = cos(t) ;
        >> hold on
        >> fill(x, y, 'red')
	>> plot(x, y, 'yellow'), title('Pentagon')
        >> axis off
        >> axis square
        >> figure(gcf)
        >> hold off
For the purposes of this example, there are only 5 points since 0 and 2*pi correspond to the same plotted point, and since we need 4 more points, we use 6 in the linspace function.

Another function function in MatLab that plots functions is fplot. This is especially useful for plotting user defined function (M-Files). For example, the function from Session 4, f(x) = x2 - 1/x, called f could be plotted as follows:

        >> clf
	>> fplot('f', [-1 1])
        >> figure(gcf)
The first argument for fplot is a string naming the function, the second argument is a vector specifying the x-axis limits for the plot. Also, the string can include a variable x and a designation for the y-axis limits if desired:
	>> fplot('f(x)', [-1 1 -5 5])
        >> figure(gcf)
Addtionally, a linetype can be added as a third argument (see plot above). For simple functions of x that can be expressed as a single character string, we can plot the function without creating a M-File using fplot. This makes it very convenient for plotting user-defined simple functions. Here is an example:
        >> clf
	>> y = '2*exp(-x).*cos(x)' ;
	>> fplot( y, [-2*pi 2*pi], 'red')
	>> title(y), xlabel('x')
        >> figure(gcf)
(Note the use of the .* operator.)

Another use of fplot is the following:
[x y] = fplot(...)
where the abscissae and ordinates for the function are returned in the column vectors x and y. No plot is drawn on the screen. The function can then be plotted with plot(x,y).

We will conclude this session with a discussion of the subplot function. Above we saw plots in multiple figure windows, and we saw plots of several functions on one coordinate axes system in one figure window. Now, subplot breaks the figure window into an m-by-n matrix or array of small rectangular panes, each capable of containing its own coordinate axes and plots. In the following example we will plot the Cartesian and polar functions (demonstrated above) in the same figure window, but on different coordinate systems:

        >> clf
	>> t = 0:0.01:2*pi ;
	>> x = sin(2*t) ;
	>> y = cos(3*t) ;
	>> subplot(1,2,1)
	>> plot(x, y), title('Cartesian')
	>> [theta rho] = cart2pol(x, y) ;
	>> subplot(1,2,2)
	>> polar(theta, rho), title('Polar')
        >> figure(gcf)
In this case we created two plots side by side (one row, 2 columns). In general, subplot( m, n, p) creates m-rows and n-columns and makes the pth pane the current plotting focus. These panes are indexed along the top row first, then the second row, etc.
We can clear the figure window with either clf or we can restore the default configuration with subplot(1, 1, 1).

					  End of Session 5.


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 



Session 6

 ________________________________

Matrices, Systems of Equations


MatLab Commands, Functions, Operations covered in this Session:
FUNCTIONS:
det
inv
eye
OPERATORS:
\ matrix left div.
* matrix mult.

The underlying data structure for most of MatLab's operations and functions is the matrix. A matrix is a rectangular array of numbers: for example,

	[ 1 2 3 ]
	[ 4 5 6 ]
defines a matrix with 2 rows, 3 columns, 6 elements. Every Matlab variable refers to a matrix, even a number is a 1 row by 1 column matrix.

To enter a matrix in MatLab we use the brackets, [ ], and semi-colons, ;, to separate the rows. A matrix is entered in "row-major order", i.e., all of the first row, then all of the second row, etc. The elements are separated from each other by spaces or by commas. Here is a 2 row by 3 column matrix assigned to a:

	>> a = [1,2,3; 4 5 6]

The element in the i'th row and j'th column of a is referred to by naming the row-column pair in parentheses following the matrix variable:
        >> a(1,2)     %element in row 1 and column 2
It's very easy to modify matrices:
	>> a(2,3) = 10

Without explaining everything about matrices at this time (you may take a course in Linear Algebra at some point in your studies where the study of matrices is rigorously examined) we will use matrices in MatLab to solve systems of linear equations. To illustrate consider the following example:


     John works part time for an establishment that is open 24 hours
     per day.  Each week he may be asked to work days, swing shift,
     or grave yard and he is paid different rates for each shift.
     Last week he worked 10 hours on days, 5 hours
     swing shift, and 5 hours grave yard and earned $152.50.  The
     week before he worked 12 hours on days, 6 hours swing shift,
     and 2 hours grave yard and earned $147.  The week before that
     John worked 8 hours on days, 12 hours swing shift, no
     grave yard hours, and earned $146.  How much does John earn
     per hour on days? on swing shift? on grave yard?

To solve this problem, write each statement as an equation. If we let x1 be his hourly rate on days, x2 his hourly rate on swing shift, and x3 his rate on grave yard, then

     10x1 +  5x2 + 5x3 = 152.50
     12x1 +  6x2 + 2x3 = 147.00
      8x1 + 12x2 + 0x3 = 146.00
represents the conditions stated in the problem. One of the main uses of matrices is in representing such systems of linear equations. The system of three equations given above could be represented as follows:
       [10  5  5]     [x1]     [152.50]
       [12  6  2]  *  [x2]  =  [147.00]
       [ 8 12  0]     [x3]     [146.00]
where the 3 rows by 3 column matrix is the matrix of the coefficients of the equations, the matrix of x's is a column matrix, and the final matrix is also a column matrix of the "right-hand sides" of the equations. If A is a matrix containing the coefficients of a system of linear equations, x is a column vector containing the "unknowns," and b is the column vector of "right-hand sides," the constant terms, then the matrix equation
A * x =b
represents the system of equations. Matlab provides a matrix operation for solving such a system of linear equations:
        >> x = A \ b
This can be read "x = A divided into b", or in linear algebra "x equals A-inverse times b."

Here is how we solve the above system of equations:

        >> A = [10 5 5; 12 6 2; 8 12 0]
        >> b = [152.50; 147.00; 146]   % a column vector
        >> x = A \ b
Write your results in the boxes below:

x1 =

_________________________________

x2 =

_________________________________
x3 =
_________________________________
		Write your answers on the printed copy.

Not all systems of equations have a solution and sometimes they have more than one (unique) solution. Systems like the above have a unique solution wherever the determinant of the coefficient matrix, A, is nonzero. In MatLab we can test this with the det function as follows:

        >> det(A)
When det(A) is nonzero (as it is in the above example), the inverse of A can be found and the system of equations can be solved either by
        >> x = inv(A)*b    % inverse of A times b
or (the way we did it above)
        >> x = A \ b       % matrix left division 
MatLab recommends the left divison operator over the inv function for reasons that have to do with the way MatLab works. It is interesting, however, to multiply the two matrices, A and inv(A), together to get the identity matrix.
        >> Identity = A * inv(A)
        >> I = eye(3)
As you see, the multiplication operator is overloaded to handle matrices, and the function eye also returns the identity matrix.

For more practice, you should solve the following problems:

     1x1 +  2x2 + 3x3 = 12
     4x1 +  5x2 + 6x3 = 36
     7x1 +  8x2 + 0x3 = 33



     Joanna works part time for an establishment that is open 24 hours
     per day.  Each week she may be asked to work days, swing shift,
     or grave yard and she is paid different rates for each shift.
     Last week she worked 14 hours on days, 4 hours
     swing shift, and 2 hours grave yard and earned $150.50.  The
     week before she worked 8 hours on days, 6 hours swing shift,
     and 6 hours grave yard and earned $157.  The week before that
     Joanna worked 10 hours on days, no hours swing shift, 10
     grave yard hours, and earned $157.50.  How much does Joanna earn
     per hour on days? on swing shift? on grave yard?



     A parabola given by the equation y = ax2 + bx + c
     passes through the points (0, -3), (1, -2), and (-1, -6).
     Find the exact equation of the parabola. (Hint: substitute the
     coordinates of the points into the generic equation to get
     a system of three equations in three unknowns, one for each
     point; the unknowns will be a, b, and c which
     you can then substitute in the generic equation to get your
     answer.)

					  End of Session 6.



This document last modified: May 15, 2004.
By Thomas M. Green
Contra Costa College
San Pablo, CA 94806
Permission to use this document is granted so long as
the author is acknowledged.

Teachers: Provide your students with a printed copy of these pages as they work
through the examples at a computer running MatLab. They can enter their results on
the printed pages for you to check and you can also ask for printouts of various graphs,
M-Files, and copies of their work sessions when they use the 'diary' command.

Please send comments and suggestions to:
Thomas M. Green c/o CCC Math Dept. hwalters@contracosta.edu


		     Double click one of the following.
[ Getting Started | First Session | Session 2 | Session 3 | Session 4 | Session 5 | Session 6 ]

Go To Math Dept. Home Page 

 Contra Costa College MatLab Stuff 


Q. E. D.


Thomas M. Green