CHAPTER 2

Basic Procedures in Using MATLAB



2.1 Discussion

MATLAB is a powerful set of programs that make a lot of operations that would be tedious in FORTRAN very straight forward. The programs run in an interpretive mode (like Basic and APL,) so much of the effort required to determine exactly what size to make arrays in FORTRAN is avoided. In addition, debugging is very simple since you can test programs and instructions line by line to see exactly what they do. MATLAB plots function in a very direct way. We will use this to look at most of our results from calculations in MATLAB. Another feature of using the language on a Unix workstation is the fact that you can open as many windows as needed to:

1) issue MATLAB commands in one,
2) see the results of graphics in another,
3) create and change MATLAB programs in others.

The User's Guide for MATLAB is quite well written and contains both a Tutorial and a Reference section. Both are quite brief so that until you learn the basic procedures and the names of a lot of functions, you will find that you have to spend considerable time looking for ways to use the language. These notes were written to help students get the background to understand how to do many of the basic operations, but you will find many other features in the Study Guide and a description of most of the functions available to help you

This chapter will demonstrate the following MATLAB procedures.

2.1 Discussion
2.2 Entering MATLAB and Using help and demo
2.3 Defining Arrays and Arithmetic Operations with them
2.4 Saving and Printing your Work
2.5 Matrix Operations with Arrays
2.6 Element by Element Operations on Arrays
2.7 Plotting Results
2.8 Find Roots of Equations: Using Polynomial Approximations

2.2 Entering MATLAB and Using help and demo



To get into MATLAB you simply open the main menu in the gray part of the screen with the right mouse button. Darken the MATLAB bar in the menu by pointing to it with the right button held down and let go of the button. If you want your MATLAB session to access a directory of yours other than your home directory, you can change directories while in MATLAB by using the cd, command. (See help cd). Files can then be saved to this directory and be loaded or referenced from it . Entering MATLAB is much simpler to do than to describe and should become automatic after a few sessions. Immediately after opening MATLAB, a MATLAB Command Window, should appear for you to work in.

You will get a message that includes information like:
  To get started, type one of these commands: helpwin, helpdesk, or demo.

  For information on all of the MathWorks products, type tour.




The demo command shows how to use a variety of Matlab tools with emphasis on array operations and graphics.

There is one inconsistency in the way a number of things are presented in MATLAB. Most messages about MATLAB functions (such as those that you get from HELP) capitalize function names, but MATLAB is case sensitive in its default state. The computer will only respond to function names that are typed in lower case. Thus to get HELP from the helpdesk or to run the DEMO packages, you must type these as helpdesk, and demo.

>> demo 

will allow you to choose maong many MATLAB 5.1 demonstration programs which construct many interesting and detailed graphs. They also give a good description of how MATLAB works. You are urged to try several of these to get some feeling for what can be done with MATLAB. In particular note how very simple programs can produce rather sophisticated results.

To get out of MATLAB, type:

>> quit

and all MATLAB windows should disappear.



2.3 Defining Arrays and Arithmetic Operations with them


MATLAB allows you to define three types of arrays:

1) scalars with a single element,
2) vectors containing ordered lists of elements,
3) matrices with ordered elements in a rectangular arrangement.

The elements stored in the arrays may be numeric or character types. No distinction is made between integer and real numbers. Numeric and character scalars may be defined using commands similar to FORTRAN. The following session will show that MATLAB automatically echoes the values you set unless you end your variable definition with a semicolon.

>> s=1.2 

s = 

    1.2000     <-- s is a numberic vector with one element in it.

>> s=1.2; 

>> s 

s = 

    1.2000 

>> a='qwerty' 

a = 

    qwerty    <-- a is a character string with the characters: qwerty in it  

Since the form used to show the value is rather verbose, you will usually want to end array definitions with a semicolon. If you forget this and start listing a very long array, simply press CONTROL C to terminate the listing. You will also find that MATLAB inserts blank lines to separate commands unless you instruct it to eliminate them with the command:

>> format compact 

As in the second example defining s, you can always see what a variable's value is by typing its name.

Let's define a few vectors:

>> v=[1 2 3] 

v = 

    1    2    3  <-- v is a numeric vector with three elements

>> vc=['asdf' '123'] 

vc = 

    asdf123  <-- vc is a character string with the characters: asdf123 in it

The square brackets must be used in defining numeric vectors and may be useful in constructing character arrays. A character vector (or string) consists of any linear arrangement of characters, so adding more characters takes place by direct concatenation.

Now finally, some matrices:

>> m=[1 2 3 

      4 5 6] 

m = 

    1    2    3 

    4    5    6 

>> mc=['asdf' 

       '123 '] 

mc = 

asdf 

123 

Suppose you want to see the names of the variables that you have created:

>> who 



Your variables are: 

a         m         n         v 

demos     mc        s         vc 

Some of these names are familiar: a, m, mc, v, and vc, were created in the sessions shown here. The variables demos, and n, must have been created when the demo command was tried.

We will show some of the more important properties of arithmetic operations with arrays, in the following session: First, a short way to get a vector of numbers of the form:

		a, a + 1, a + 2, .  . . b - a, b

then some operations on that vector to show how vector functions make life easy in MATLAB. Set t as a vector with elements at a regular spacing. Choosing:

          a=0,   interval=0.5,  b=2

 

>>  t=0:.5:2 

t = 

        0    0.5000   1.0000    1.5000    2.0000 

>>  2*t 

ans = 

        0    1     2     3      4 

>>  f=sin(t) 

f = 

        0    0.4794   0.8415    0.9975    0.9093 



2.4 Saving and Printing your Work


If you run out of time to finish a problem in MATLAB, you should save the workspace by typing:

>> save 

which produces a file called matlab.mat., This may then be retrieved by:

>> load 

when you can continue work on the problem. If you have several problems that you want separate workspaces for, simply give them different names as in:

>> save prob1 

which can be retrieved by:

>> load prob1 

If you want to start over with a fresh workspace, type:

>> clear 

If you want to get rid of only a few variables in your active workspace, give the names of the variables to be deleted after the clear, command. You can also save only a few of the variables in a named workspace by listing the names of those variables after the workspace name in the save command.

Note that when you use the save, command, you create a binary file that can not be listed or edited or otherwise used in another environment. If you have a long numeric array that you want to save so that it can be used in another environment, save that variable with the command:

>> save name.dat name -ascii

This will create a file called name.dat, with the data that was in the MATLAB variable name, stored so that it can be listed, edited or used elsewhere as any other ASCII file. It can also be loaded back into MATLAB to create the numeric array with the same data in it or with new data if the file has been edited.

Here is an example where the variable xm, is saved, then the resulting file is edited to add more data. In MATLAB the array listed as:

xm = 

 

          12          15          17          19 

           2          -3          -5         -15 

         100       10000     1000000   100000000 

It was saved by:

>> save xm.dat xm -ascii

to produce the file xm.dat, that lists as:

wsname% cat xm.dat 

1.2000000e+01   1.5000000e+01   1.7000000e+01   1.9000000e+01 

2.0000000e+00  -3.0000000e+00  -5.0000000e+00  -1.5000000e+01 

1.0000000e+02   1.0000000e+04   1.0000000e+06   1.0000000e+08 

 

Suppose we edit it to add another row:

wsname% cat xm.dat 

1.2000000e+01   1.5000000e+01   1.7000000e+01   1.9000000e+01 

2.0000000e+00  -3.0000000e+00  -5.0000000e+00  -1.5000000e+01 

1.0000000e+02   1.0000000e+04   1.0000000e+06   1.0000000e+08 

   400             10.5            -18              0 

Then in MATLAB we can get this new version of the variable by:

>> clear 

>> load xm.dat 

>> format short e 

>> xm 

xm = 

1.2000e+01   1.5000e+01   1.7000e+01   1.9000e+01 

2.0000e+00  -3.0000e+00  -5.0000e+00  -1.5000e+01 

1.0000e+02   1.0000e+04   1.0000e+06   1.0000e+08 

4.0000e+02   1.0500e+01  -1.8000e+01            0 

If you want to save a copy of your session in a file for someone to study or to print, you can do so by starting the session with the diary, command. This is shown in the following example session:

>> diary mat1.t 

>> t=0:.1:6; 

>> plot(t,sin(t)^2) 



??? Error using ==> ^ 

Matrix must be square. 



>> plot(t,sin(t).^2) 

>> quit 

  183 flops 

Note the error in the squaring operation. The omitted period is one of the most common errors in MATLAB. We wanted an element by element operation on an array and must specify that.

The file mat1.t, will then list exactly like the session just shown with only the line involving diary missing. The graphics window will show your curve with axes marked at integer or simple fractions. Try the commands shown in the example session to see how simple the use of diary, and plot, is. If you save several sessions in the same file, new ones are appended. Of course, the graphics output is not saved. The recording in the file may be turned on and off with the commands:

>> diary off 

any commands that you do not want saved

>> diary on

The diary command rarely produces a file that is suitable for submission as a solution to assignments. In nearly all cases such files include rough output with numerous errors and statements out of order so that a grader can not follow what was done in completing the assignment. You should always plan to edit such files to make it clear by adding comments, reordering the output and deleting errors so that the results are easier to follow. In particular, you should show in the file the problem that is being worked and clearly designate the final answers to the problem. You may find it easier to make assignment solutions by copying the results in a Matlab or Maple session to a file that you are editing as you complete the assignment. When assignments are ready for submission, they should be stored in a file in your ceng301/ceng303 directory and clearly labeled with a name that tells what is in the file. For example, assignment 1 solution might be called solution1. When the file is ready to be graded, your TA should be sent an e-mail message telling her/him that the file is now ready for grading.




2.5 Matrix Operations with Arrays


There are two kinds of operations with arrays called: Matrix operations and Array operations. The first set includes taking the transpose of an array, ``matrix" multiply, adding and subtracting arrays of the same shape, etc. The transpose of a matrix is found with the single quote symbol . Matrix multiply is done with a * and addition and subtraction use their normal symbols as seen in the following:

>> m' 

ans = 

     1    4 

     2    5 

     3    6 

>> m*v' 

ans = 

    14 

    32 

>> m1=[6 5 4 

       7 4 1]; 

>> m+m1 

ans = 

     7    7    7 

    11    9    7 

Finally matrix division is used to solve sets of linear equations. To solve the set of equations:

	5x1 + 3x2 -  x3 =  5

	2x1 - 7x2 - 3x3 =  0

	 x1 + 5x2 + 6x3 = -7

we need to define a 3 by 3 matrix with the coefficients of the unknowns in it and divide a column vector with the right hand side coefficients by this matrix. Unfortunately you have to get used to the fact that there are two divide symbols in MATLAB.

A\B gives the solution to: A*X = B
A/B
gives the solution to: X*A = B

In our case we need to use the first form so:

>> a=[5 3 -1 

      2 -7 -3 

      1 5  6];

>> a\[5 0 -7]'   <-- Note the quote or prime 

                  to transpose the vector.

ans = 

    0.1168 

    0.8426 

   -1.8883 

 

We can confirm our solution by using matrix multiply.

 

>> a*ans 

ans = 

    5.0000 

    0.0000 

   -7.0000 

If we forget how many elements there are in a vector, the command length, will tell us. The size, command will tell how many rows and columns there are in a defined matrix. These are shown in the following session:

>> v=[1 3 5]; 

>> size(v) 

ans = 

     1     3 

>> length(v) 

ans = 

     3 


2.6 Element by Element Operations on Arrays


Array operations in MATLAB require some care. Essentially there are two types of operations involving arrays.

1) Element by element operations
2) Vector-Matrix operations.

Confusing these can lead to real difficulties. The next session shows the formation and addition of two vectors:

>> a=[1 2 3]; 

>> b=[2 5 8]; 

>> a+b 

ans = 

     3     7    11 

Now suppose we try to multiply them:

>> a*b 



??? Error using ==> * 

Inner matrix dimensions must agree. 

What happened? The multiplication symbol by itself when applied to vectors or matrices is interpreted to mean matrix multiply. We could have done this by transposing the second vector:

>> a*b' 

ans = 

    36 

 

This gave (1*2 + 2*5 + 3*8) = 36, the usual scalar product of two vectors.
If we want the element by element product, we must put a period before the multiplication symbol:

>> a.*b 

ans = 

     2    10    24 

 

The same procedure must be followed in doing division and exponentiation. For example, if you want the square of each element in a vector you must use:

>> a.^2 

ans = 

     1     4     9 

Forgetting the period will lead to:

>> a^2 



??? Error using ==> ^ 

Matrix must be square. 

The fact that MATLAB gives vector and array results with most of its built-in functions is one of its main features. The fact that sin(t), with t, a vector gives the value of sin of each element makes it trivial to look at a plot of the function.



2.7 Plotting Results


The following set of commands produces a plot of sin(t) and cos(t) for t from 0 to 4pi.

>> t=0:pi/16:4*pi; 
>> plot(t,[sin(t);cos(t)]) 
>> title('sin(t) and cos(t)') 
>> xlabel('t') 
>> ylabel('sin and cos') 


Figure 2.1 Sin(t) and Cos(t)

The five lines in this sequence do the following:

1) Sets up a vector t with the elements: 0, pi/16, pi/8, .... 4pi.
2) Creates a matrix with its first row: sin(0),sin(/16),sin(/8)...sin(4). and its second row: cos(0),cos(/16),cos(/8)...cos(4). and plots the two curves.
3) Puts a title at the top of the plot.
4) Labels the x axis.
5) Labels the y axis.

If you want to save your figure to use in a later Matlab session or for someone else to see in such a session use the Save As command in the file menu on the plot figure. This will save the figure with the name you specify and an appendage of .fig. You may then retreive the file with the open command in another Matlab session.

Two three dimensional plotting routines are available. Both are demonstrated in the EXPO package. The mesh, command constructs a three dimensional plot of the values in a matrix vs the indices that specify positions in the matrix. The contour, command gives a contour plot of a matrix interpreted in the same way.

You can create up to four subplots in the same window. The first two digits in the argument of subplot, specify how many plots and their orientation as:

First Two Digits

No. of Plots

Orientation

12
Two

side by side

21
Two

above and below

22
Four

in the Quadrants


The last digit then specifies the particular plot.



2.8 Find Roots of Equations: Using Polynomial Approximations


We will demonstrate several MATLAB functions in this section. You may find them useful in solving a variety of problems, but our demonstration will show simply how to find a root of one equation. The typical problem is: find x such that f(x)=0. Our demonstration will be concerned with finding a root of sin(x)=0. We know there are roots at 0 and all multiples of . In more complicated problems we would not know that however and might have to spend some time determining just what intervals to search for a root. Let's start by looking at a plot of our function:

>> t=0:.1:6;

>> plot(t,sin(t))

>> grid 


Try that and you can see that there is a root between 3 and 4:


Figure 2.2 Looking for a root

We could redefine t to span the interval (3,4) and plot that result to home in on the root, but will investigate using a polynomial fit of the values for our function:

>> t=3:.25:4; 

>> c=polyfit(t,sin(t),3)

c = 

    0.1537   -1.4420    3.5107    -1.5619 

>> roots(c) 

ans = 

     5.6727 

     3.1415 

     0.5704 

The polyfit, function finds a polynomial that fits the data given it in the least squares sense. In our case, it found that:

    p(t) = 0.1537t^3 - 1.4420t^2 + 3.5107t - 1.5619 


closely approximates sin(t) over the interval (3,4). The program roots finds all roots of a polynomial. We can recognize that the procedure found an answer very close to the one that we know is correct: .


Continue on to Chapter 3
Return to Table of Contents