Peer Training: Introduction to MATLAB

 

 

 

 

 

 

MATLAB, a product of Mathworks, is a software widely used for exploring, refining, and understanding the numerical algorithms used in many scientific and technological fields. Engineers nowadays can hardly survive without the use of MATLAB as a test platform for their codes. Useful applications in different fields include processing of medical images, stress and strain study in structural mechanics, earthquake data analysis in seismology, reaction-diffusion processes in ecology and kinetic chemistry, and Markov processes in mathematical economy. MATLAB, an acronym for MATRIX LABORATORY, is also very efficient at visualizing pure mathematical problems. Complicated non-linear equations, differential and integral equations, and evaluation of integrals can all be solved numerically, and to a good extent symbolically.

 

MATLAB is mainly a programming language. However, in contrast to many programming languages, MATLAB is extremely easy to use. It is flexible to the userís needs and requires almost no so-called ďprogramming skills.Ē For the expert, MATLAB is an interpreted language but can also be translated to C or C++ code if desired. We will not discuss this advanced topic in this session.

 

This class provides you with basic manipulations and techniques for the use of MATLAB. It is assumed that you have some knowledge of elementary Calculus and that you know the concept of vector (although we will give a brief review of it). This tutorial is intended for MATLAB on a PC/Windows workstation, but if you need information about Macs or Unix, do no hesitate to ask.

 

This course lasts for three hours and is structured into three parts. There will be two breaks of five to ten minutes each hour.

 

Please stop the instructors and ask for explanations if something is not clear or is not working properly!


 

 

 

MATLAB Course Outline

 

 

Part 1: Elementary Steps

1.     Starting Up and Closing Down

2.     Asking for Help

3.     Command Line Editing

4.     Matrices and Vectors

5.     Basic Operations

6.     Scalar Functions

7.     Array Operations (dot notation)

8. Matrix and Vector Functions

9.     Examples

 

Part 2: Graphics, Output Format, and Symbolic Computations

1.     Two Dimensional Graphics

2.     Symbolic Computations

3.     Exercises

 

Part 3: Programming with MATLAB

1.     The M-files

2.     Loops and Conditions: For, While, If Loops

3.     Exercises

 

Part 4: Managing MATLAB

1. Printing and Exporting

2. Saving and loading MATLAB sessions

3. Submitting MATLAB work

 


 

 

Part 1: Elementary Steps

 

1. Starting Up and Closing Down

 

A. How to Start?

 

MATLAB can be used in both interactive and silent modes. During this class we will be operating in the more commonly used interactive mode.

 

If you are on a Windows workstation, click on the Start button. A pop-up menu will fly out. Select successively Programs, Applications, and then MATLAB 5.3.

 

If you are on a different PC, click on Start, then Find (Files or Folders) and look for MATLAB through the dialog window. Double click on the MATLAB file.

 

After some loading time (usually 10 to 30 seconds), the MATLAB Command Window will appear. The command window in MATLAB is referred to as the shell. You will see the following output on your shell:

 

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

 

 

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

 

 

 

>>

 

This is MATLAB's greeting as the program begins.

 

Remark: Always check the Version number when you are using MATLAB on a different network. This can be done by typing:

 

>> version

 

B. How to End?

 

You can end a MATLAB session with the command line:

 

>> quit

 

Exit will also work. Either one of these commands will bring you back to the shell prompt.

 

 

2. Asking for Help

 

A. MATLAB Online Manual

 

There are several ways for getting help with MATLAB. A good way to start is to type:

 

>> helpdesk

 

The helpdesk command opens an HTML document, which contains the MATLAB reference book. This is quite a large documentódonít be overwhelmed! Useful sections for beginners include Getting Started and MATLAB Functions. You might want to browse them before beginning your first session.

 

Itís helpful to keep this browser window open while you are working with MATLAB, so that you can refer to it easily.

 

B. Other Sources of Help

 

There are other ways of getting help with MATLAB that do not make you search through the whole reference book. If you already know the name of a MATLAB Function--for example, quit--and you want to learn about its use, enter:

 

>> help quit

 

You will see a description of the command quit.

 

During your first experiences with MATLAB you should from time to time take a:

 

>> demo

 

session which will show you various features of MATLAB.

 

Another very useful feature is the lookfor command. It looks for all the commands related to a given topic. Try:

 

>> lookfor 'help'

 

It will list all of the commands we just discussed.

 

 

3. Command Line Editing

 

A. Command lines

 

Once you open a MATLAB session, you start entering command lines. A command line consists of one or more statements separated by a semicolon. A statement is defined as "the smallest executable piece of MATLAB code.Ē

 

We already saw some examples of command lines above, other examples are:

 

>> sqrt(2)

 

(which extracts the square root of 2 and returns it as an output)

or:

 

>> A = sqrt(2);

 

(this assigns to the variable A the value of square root of 2).

 

Observations:

1. When you enter the command lines the >> should not be typed in. This is not part of the command line, but rather indicates its beginning.

2. Every command line terminates with a <return> (or <enter> if you prefer).

3. MATLAB has very flexible syntax, and the same command line can be entered in different ways. We will discuss this more later.

4. A single command line can contain more statements. For example:

sqrt(2); B = 3;

5. Notice that the <return> should be typed in only at the end of the command line.

 

B. The use of the semicolon

 

If you tried to type in the three command lines above you may have noticed some differences in MATLABís reaction to them. For example:

 

>> sqrt(2)

 

furnishes the output:

 

ans =

1.4142

 

whereas the command line:

 

>> A = sqrt(2);

 

seems to have no effect. Actually it has, but we do not see the effect because of the semicolon ";" at the end of the command line. The semicolon is a request for MATLAB not to show the outcome of the operation. This is useful in programs when MATLAB performs a lot of intermediary calculations.

 

The command line above is an assignment operation. To make sure that MATLAB performed it just type in:

 

>> A

 

and the output should read:

 

A =

1.4142

 

This would have been the output of the command line defining A if we hadn't typed the semicolon at the end of the command line.

 

C. Recalling old command lines

 

During a MATLAB interactive session it is possible to recall one of the former command lines by typing <arrow up> as many times as needed to reach the desired line. This feature can save a lot of time, especially if a simple command line must be repeated many times. The <arrow down> key will scroll down the history of command lines.

 

Try this command to recall what you have entered in your MATLAB session so far.

 

D. Stopping MATLAB calculations

 

Often one needs to interrupt MATLAB while it is computing. This is done by typing

<control> and C at the same time.

 

E. Variables

 

When creating a large matrix, it is useful to name it with a variable name.

 

Upper or lower case letters can be used to form a variable name. They can contain digits, but not in the first position. All other characters (space included) are not allowed in variable names. The only non-alphanumeric character that is allowed is the underscore "_" which is used in accordance to tradition as a space since the latter is not allowed.

 

Examples:

Legal choices for variable names in MATLAB are M , m , A , Wronsk , _A , WRONSK , wRoNsK , Wronsk_A , w1 , w0 , w234i , f_prime etc. Notice that some of these, although legal, are not really aesthetic.

 

The following are illegal choices for variable names in MATLAB: 2 , #2 , a# , Wronsk! , Wronsk A , w@1 , w1,2 , f' etc.

 

Remark: MATLAB distinguishes between upper and lower case letters! All the variables above are different.

 

To use variables, we type the variable name followed by an equals sign, followed by what we want that variable to represent. For instance:

 

>> myvariable=3

 

And the computer will respond with:

 

myvariable =

3

 

There are a few commands that make managing the variables you use easier.

 

>> who

 

will list the variables you have used:

 

Your variables are:

 

A myvariable

 

While the command:

 

>>whos

 

will list the variables you have used, along with some other pertinent information, including the size of the matrix that the variable represents, the type of variable, and the amount of memory taken up by that variable:

 

Name Size Bytes Class

 

A 1x1 8 double array

myvariable 1x1 8 double array

 

Grand total is 2 elements using 16 bytes

 

* Remember, MATLAB stores ALL variables as matrices, including single numbers (which are recorded as 1x1 matrices).

 

Finally, if we want to clear one or all of our variables, we use:

 

>>clear myvariable

 

or:

 

>>clear all

 

to clear all of our variables we have used.

 

If we want to see what a variable is designated as, we type the variable name:

 

>>A

 

A =

 

1.4142

 

There is one other type of variable we will be discussing later in the class, which is the 'symbolic variable.' Using symbolic variables, we are able to solve equations symbolically instead of numerically.

 

 

4. Matrices and Vectors

 

A. Matrices

 

The basic data structures that MATLAB uses are objects known as matrices. A matrix is a rectangular table consisting of numbers. These numbers are referred to as entries or elements of the matrix. Matrices are very handy objects widely used in mathematical applications and are very simple conveyors of information. An example of a matrix is:

 

1 3 4 5

-1 0 2 2

1 -1 -1 1

 

Since this matrix has three rows and four columns, it is referred to as a 3x4 (three by four) matrix.

 

The entries of a matrix have their position identified by the number of the column and the number of the row they sit in. For example, in the matrix above, the [3,2] entry is -1, and the [2,3] entry is 2.

 

To enter the above matrix in MATLAB we type:

 

>> M = [1 3 4 5; -1 0 2 2; 1 -1 -1 1]

 

or alternatively:

 

>> M = [1 3 4 5

-1 0 2 2

0 2 2 2]

 

B. Building matrices

 

MATLAB provides a lot of different ways for generating matrices and vectors. Some are built-in functions. Try the following matrix constructions:

 

>> Noise = rand(4)

 

>> diag([1 4 5 6 -1])

 

>> I = eye(3)

 

>> zeros(2,4)

 

There are many other built-in matrix building functions, and as you become more expert you will be able to define your private ones.

 

Remark: When you enter matrices you are not required to assign a variable name to them. Although this can sometimes be useful (such as when you try new commands), it is poor practice when effectively using MATLAB.

 

C. Building vectors

 

Since vectors form a particular subclass of matrices, all that has been said about matrices applies to vectors (with the appropriate restrictions). For example:

 

>> zeros(1,3)

 

will construct a row vector of length 3 whose entries are zeros.

 

However, an easier way to build vectors is by using the colon " : " vector builder.

 

The colon builder has two required arguments: the starting point and the ending point.

For example, the following command line:

 

>> v = 1:9

 

yields:

 

v =

 

1 2 3 4 5 6 7 8 9

 

The colon builder can be made more sophisticated by adding a third (optional argument) between the starting and ending point. This argument indicates the stepsize. For instance:

 

>> w = 1:0.5:9

 

yields:

 

w =

 

Columns 1 through 7

1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000

Columns 8 through 14

4.5000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000

Columns 15 through 17

8.0000 8.5000 9.0000

 

Remark: The output of the last example looks quite different from the previous one. There are two reasons for this:

 

1. The vector v consisted solely of integer entries. This makes MATLAB output its entries in the integer format, while the entries of the vector w are in floating point format. The floating point format is how computers understand what we usually call decimal numbers. Sometime these are incorrectly called real numbers.

 

2. The vector v is shorter than w, and MATLAB was able to write it out in one single line. This type of output was not possible for the vector w because the screen is too small, and the row vector was thus split into several lines. However, since these several lines still represent a single row, MATLAB indicates this fact by appending the "Columns n through n+k " label above each line.

 

D. Accessing and manipulating entries

 

Consider the matrix:

 

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

 

M =

 

1 2 3

 

 

6 3 4

 

 

5 4 3

 

and suppose that we are interested in accessing the entry sitting in row 2 and column 3 (the value being 4). We type in:

 

>> M(2,3)

 

ans =

 

4

 

Remark: Notice the way we entered the matrix M, using commas and semicolons.

 

Exercise: Access the entries (1,2), (2,1) and (4,1) of the matrix M above.

The entries of a matrix can also be modified. For example:

 

>> M(2,3)=-1

 

M =

 

1 2 3

 

 

2 3 -1

 

 

5 4 3

 

Exercise: Set the entries (1,2) and (2,1) of to -12 and 56, respectively.

 

We can also access the entries of a matrix not only individually but also in blocks (called submatrices). Assume for example that we are given the matrix:

 

>> A = rand(4)

 

then if we wanted to remove the 3x3 matrix consisting of the first three rows of the last three columns, we would type:

 

>> B = A(1:3,2:4)

 

To get the second row or fourth column of A we enter, respectively:

 

>> second_row = A(2,:)

 

>> fourth_col = A(:,4)

 

This syntax can be used also to modify the entries, for example:

 

>> clear A

 

>> A(1,:) = 1:7

 

>> clear A

 

>> A(:,1) = (1:7)'

 

 

5. Basic Operations

 

Matrices, vectors and scalars can be added, subtracted and multiplied. Scalars can be divided, and we will see that matrices and vectors can also be divided.

 

A. Scalar operations

 

Operations on scalars with MATLAB resemble those performed by pocket calculators. Here are some examples to try:

 

>> 2+3

 

>> 2-3

 

>> 2*3

 

>> 3/2

 

>> a = 4; b = 5; c = a*b

 

>> a+b

 

>> c = c+1

 

Remark: The last statement may look like nonsense to those who are not used to computer programming languages. Indeed, if you consider that statement as a mathematical equality, it is impossible to find a number c that equals itself plus one. However, in MATLAB and most of the computer languages, the sign " = " does not mean equality but means assignment. The last statement makes MATLAB perform the following logical sequence of operations:

 

take the current value of the variable c;

add 1 to this value;

reassign the result as a new value for c.

 

B. Matrix Addition

 

Two matrices, M1 and M2, can be summed and subtracted but they must meet the

 

sum-compatibility requirement

the number of columns of M1 must equal the number of columns of M2, and

the number of rows of M1 must equal the number of rows of M2.

 

In particular, two row vectors can be added (or subtracted) if they have the same length and column vectors can be added (or subtracted) if they have the same size.

 

Here are some examples to try:

 

>> [1,2;3,4]+[2,1;0,4]

 

>> A=[1,2;3,4];B=[2,1;0,4];C=A+B

 

>> A-B

 

>> A = A + B

 

>> v=1:7;w=7:-1:1;v+w

 

>> v-w

 

>> u=[1 2 3 3 2 1]

 

>> u+v

 

Trouble?

 

A useful matrix function that helps us to understand if two matrices can be summed is the size function. For example:

 

>> size(u)

 

ans =

 

1 6

 

while:

 

>> size(v)

 

ans =

 

1 7

 

The first output tells us that u has 1 row and 6 columns, while the second output tells us that v has 1 row and 7 columns. We cannot sum these two vectors!

 

C. Row-by-Column Matrix Multiplication

 

Note: We will not go into the details of Matrix Algebra. This is a topic that is covered in elementary courses of Linear Algebra like MATH240 at UMCP. If you have never seen matrices before today, then the next paragraph might be a little confusing to you. Nevertheless you should make an effort to follow; things will become clearer when you encounter matrices in practice.

 

Suppose you want to multiply M1 by M2. These must first meet the

 

row-by-column product compatibility requirement

The number of columns of M1 must equal the number of rows of M2.

 

Remark: It can happen that the product M1*M2 is defined while M2*M1 is not defined. Even when both products are defined they are not necessarily equal.

 

Here is a series of allowed and not allowed matrix multiplications:

 

>> M1=[1 2 -1

3 4 5];

 

 

>> M2=[2 -1

0 3

1 10];

 

>> M3=M1*M2

 

>> M4=M2*M1

 

>> M5=M2*M4

 

>> v1=[0;1;2]

 

>> w1=[-1,1]

 

>> M1*v1

 

>> w1*M1

 

>> w1*M1*v1

 

>> v1*M1

 

>> A=[1 3

4 5];

 

>> A*A

 

>> A*A*A*A*A*A*A*A*A*A*A*A*A

 

Which operations werenít possible? Why?

 

D. Power Operation

 

In the last example we could have shortened the expression to:

 

>> A^13

 

The power operation on a matrix is just a shortcut for repeated (matrix) multiplication, exactly as with scalars.

 

E. Transpose Operation

 

The transpose operation is a basic matrix manipulation which is input in MATLAB by affixing a single quote "'". This operation interchanges the row index with the column index.

 

>> v1

 

>> v1'

 

>> w1

 

>> w1'

 

>> M1

 

>> M1'

 

>> A

 

>> A'

 

Exercise: The inner product of two spatial vectors v and w described in an orthonormal reference frame as v=(vx,vy,vz), w=(wx,wy,wz) is defined as the scalar:

 

v.w = (vx wx)+(vy wy)+(vz wz).

 

Given the vectors (1,2,3) and (-2,1,3), compute their inner product by using matrix operations of MATLAB.

 

F. Scalar-by-Matrix multiplication

 

Given a matrix M1 and a scalar a, we can multiply M1*a and a*M1. The result is a matrix whose entries are the entries of M1 each multiplied by a. Example:

 

>> a = [3]; M1

 

>> a*M1

 

>> M1*a

 

Remarks:

 

In the above example even though a is entered as a matrix, MATLAB treats it as a scalar. The use of the square brackets is redundant and is put only to emphasize this observation. Normally one would type just " a = 3 ".

 

The scalar-by-matrix multiplication is commutative, unlike the row-by-column matrix multiplication.

 

The operation above is referred to sometimes as scaling the matrix M1 by a. Notice that the scaling of the matrix acts entry-wise unlike the row-by-column multiplication. The scaling of matrix is called an array operation because of this behavior.

 

G. What about scalar-by-matrix addition?

 

What happens if you type in the following command line?

 

>> c = 1000; f = [1 3 -1 4]; c+f

 

Exercise: Investigate the division of matrix by a scalar.

 

H. Matrix division: solving linear systems

 

A linear system is a problem of the type:

 

Given an n x n matrix A and a (column) vector b of size n, for which (column) vector x of size n is the equation Ax = b satisfied?

 

By basic linear algebra it is known that if A is non-singular (i.e., if det A is non zero), then this system admits one and only one solution x. It is extremely easy to compute this solution using the left division command in MATLAB:

 

>> A = [ 1 2 3

3 0 0

0 1 -1];

 

>> b=[1 1 -2]';

 

>> x=A\b

 

x =

 

0.3333

-1.0667

0.9333

 

Remark: Note that in the above example we used a backslash division bar " \ " as opposed to the traditional division bar " / ". One can use the right division operator " / " to solve the "row type" linear system:

 

Given an n x n matrix B and a (row) vector r of length n, for which (row) vector y of length n is the equation yB = r satisfied?

 

This comes from the fact that matrix multiplication is NOT commutative, unlike scalar multiplication, which is.

 

This new system is solved by typing:

 

>> y = B/r

 

Exercise: Given an n x n matrix A and column vector b of length n, what is the difference between:

 

>> x = (b'/A')'

 

and:

 

>> x = A\b

 

 

6. Scalar Functions

 

Most of MATLAB commands are functions. Some of these functions represent mathematical functions and operate on scalars as well as on matrices. Typical examples of scalar functions are the traditional elementary functions from basic calculus:

 

>> sqrt(14.407)

 

>> log(2)

 

>> sin(pi/3)

 

>> cosh(3.27)

 

>> abs(-15)

 

This last one is just the absolute value function applied to -15, denoted usually by |15|.

 

Other examples of less traditional scalar functions are:

 

>> rem(13,3)

 

>> floor(13/3)

 

>> round(13/3)

 

>> round(14/3)

 

>> ceil(13/3)

 

Very important remark: All scalar functions operate on matrices entry-wise. Matrices are viewed as arrays of numbers, and the function operates on every entry independently of the other entries. The output of a scalar function with matrix input (say of size n xm) is another matrix of the same size (n xm).

 

Examples:

 

>> A = [1 4

5 25]

 

A =

1 4

5 25

 

>> sqrt(A)

 

ans =

 

1.0000 2.0000

2.2361 5.0000

 

>> W = [10.334 12.307 -13.554 14.306]

 

W =

 

10.3340 12.3070 -13.5540 14.3060

 

>> sign(W)

 

ans =

 

1 1 -1 1

 

This feature of MATLAB makes it very easy to construct tables of function values as shown by:

 

>> x=.1:.1:1.9;log_table=[x;log(x)]'

 

or by:

 

>> x=0:pi/6:pi; y=sin(x)

 

Exercise: What do you expect the outcome of the following command line to be?

 

>> A=[1 4; 16 25];(sqrt(A))^2

 

 

7. Array Operations (dot notation)

 

The last exercise can be puzzling. Indeed, we expect that taking the square root of an object and then squaring the result will recover the original object. This works if the object is a scalar, but in the case of matrices some extra caution is needed. Consider the matrix:

 

>> M = [1 2;3 4]

 

and suppose we want to square each element of the matrix. From what we have seen in the matrix operation section, if we enter:

 

>> M^2

 

we do not obtain the desired result, but rather the result of the operation M*M . To force MATLAB to perform an entry-wise operation we use the dot notation:

 

>> M.^2

 

Try these other examples:

 

>> Z = [1 3 ; 4 1]; Y = [-2 3 ; 4 -5];

 

>> Z*Y

 

>> Z.*Y

 

Exercise: What do you expect the outcome of the following command line to be?

 

>> A=[1 4; 16 25];(sqrt(A)).^2

 

 

8. Matrix and Vector Functions

 

A. Matrix functions

 

In MATLAB, there are functions that operate on a matrix as a whole. In contrast to scalar functions applied to matrices, the output of matrix functions can be a different type of matrix than the original one. Important matrix functions are:

 

       The Determinant

 

>> M=[1,2;2,7];det(M)

 

ans =

3

 

>> A=hilb(5);det(A)

 

ans =

3.7493e-12

 

       Eigenvalues

 

>> eig(A)

 

       Inverse

 

>> inv(A)

 

       Rank

 

>> rank(A)

 

       Size (already discussed above)

 

Some matrix functions, like det, eig and inv, operate only on square matrices; and some functions, like rank or size, operate on any type of matrix (a matrix is square when the number of rows equals the number of columns).

 

B. Vector functions

 

Besides scalar functions and matrix functions, there is an intermediate class of functions: the vector functions that operate on vectors (either row or column). The following examples illustrate some of these functions. First construct randomly a vector:

 

>> v = 10*rand(1,10);

 

we can have optimization type functions:

 

>> max(v)

 

>> min(v)

 

>> sort(v)

 

or algebraic functions:

 

>> sum(v)

 

>> prod(v)

 

or statistical functions:

 

>> median(v)

 

>> mean(v)

 

>> std(v)

 

Exercise: What do you expect the outcome of:

 

>> w=rand(1,1000);mean(w)

 

to be?

 

If the operand of a vector function happens to be a matrix, then the function operates column-wise. That is, it considers every column as a single vector, and returns a row-vector containing in each column the result of the function on the corresponding column. It is clearer with an example:

 

>> A=vander(1:6)

 

>> mean(A)

 

 

9. Exercises

 

Remember: Feel free to ask the trainers for explanations!

 

Enter the following matrices

A =

1 2 -1

4 -5 2

 

B =

3 1

3 4

2 1

 

and perform the following operations if they are possible (avoid error messages):

 

C=AB, D=BTAT , det(C), det(A), find the spectrum (eigenvalues) of D.

 

Enter the vectors v = (1, 2)T and w = (1, 3, -1), decide which of the following operations are legal (avoiding error messages as much as possible) and perform them:

 

x = wB, y = AwT, z = Bv, u = vA.

 

Tabulate the cube function on the interval [-4, 4]. Try this exercise with three different step sizes: say 0.1, 0.01 and 0.001.

 

Solve the linear system:

12 x + 4 y + 3 z = 1

3 x + 2 y = -1

2 y - 4 z = 9

 

To do this you should first write it down in a matrix form, and then use the matrix division operator.

 

Generate two column vectors of length 20 with random entries between 0 and 100. Sort the first vector in ascending order and find a method to sort the second in descending order. (Hint: scaling by (-1) inverts the order of the numbers.)

 

Add the two vectors and find the median of their sum.

 

 

Part 2: Graphics, Output Format, and Symbolic Computations

 

1. Two Dimensional Graphics

 

A. The plot function

 

Suppose x and y are two vectors of same length, the command line:

 

>> plot(x,y)

 

produces a graph of the elements of x versus the elements of y. If the elements of x are in ascending order and distinct, then the graph is similar to that of a mathematical function. Otherwise the graph might be more complicated. For example:

 

>> x = -3:.1:3; y = x.^3; plot(x,y);

 

will plot the graph of the cube function on the interval [-3,3].

[image002.gif]

 


If you want to plot a parametric curve, a cardioid for instance, start by setting up a parameter vector:

 

>> t = 0:pi/30:2*pi;

 

and then give the parametric equations for the abscissa and ordinate as the arguments of plot:

 

>> plot( (1-cos(t)).*sin(t) , (1-cos(t)).*cos(t) );

[image004]
 

 

 


We don't have to plot necessarily mathematically defined functions. We can also represent results from experimental data: for example, the average maximal temperature of each month last year.

 

>> months = 1:12;

 

>> temp_max=[39,44,59,65,82,89,95,102,96,88,64,55];

 

>> plot(months,temp_max);

 

 

[image006]

 


In the last example, however, we can simplify the plot command to:

 

>> plot(temp_max);

 

Indeed, if only one argument is given, it is considered as a second argument of a plot command, while the first argument is taken to be the correspondent index vector.

 

Remark: Notice that the output of the plot function does not appear in the MATLAB shell, it appears in a graphics window. Clicking first on the File menu and then selecting the Close option will close this window.

 

B. Optional arguments

 

The plot function accepts optional arguments to control the plotting style. For example:

 

>> x = -3:.1:3; y = x.^3; plot(x,y,'o')

 

will put circles at the data points; and:

 

>> x = -3:.1:3; y = x.^3; plot(x,y,'g-.')

 

will plot a green dashed-dotted line.

 

C. Embellishments and information in plots

 

We can add some labels to the picture, for instance:

 

>> title('Green function')

 

>> text(-2,20,'Is this a green function or a Green function?')

 

>> xlabel('x-axis')

 

>> ylabel('y-axis')

 

A useful command is the so called interactive text positioning:

 

>> t = 0:pi/30:2*pi;plot( (1-cos(t)).*sin(t) , (1-cos(t)).*cos(t) );

 

>> gtext('This spot is hot!')

 

D. Other simple plotting commands

 

In addition to the command plot, MATLAB furnishes many variations. For example:

 

>> bar(temp_max,'r')

 

 

draws a bar graph:

 

[image008.gif]
and

 


>> theta = 0:pi/12:2*pi;polar(theta,2*(1-cos(theta)));

 

draws a polar graph:

 

[image010.gif]

 


Remark: One easy thing to do in MATLAB graphs is to increase the resolution of your graph. For example, if you are not satisfied with the output of the last example, try:

 

>> theta = 0:pi/36:2*pi;polar(theta,2*(1-cos(theta)));

 

E. Plotting more than one graph on the same plot

 

Sometime we would like to compare two graphs on the same picture. There are three different ways of doing this with MATLAB. Suppose we want to compare exp to its Taylor expansion of order 2, 1+x+(1/2)x2, and to that of order 3, 1+x+(1/2)x2+(1/6)x3.

 

First method

 

Define singularly the vector of values corresponding to each function:

 

>> x=-1:.02:1;

 

>> func=exp(x);second=1+x+1/2*x.^2;third=second+1/6*x.^3;

 

>> plot(x,exp(x),x,second,x,third);

 

 

 

[image012.gif]

 

 


Notice the use of the dot notation.

 

Second method

 

Define a matrix whose columns are the vector of values of the functions:

 

>> x=-1:.02:1;

 

>> Functions=[exp(x);1+x+1/2*x.^2;1+x+1/2*x.^2+1/6*x.^3]';

 

>> plot(x,Functions)

 

(Graph should be the same as above)

Notice the use of the prime notation.

 

Remark: MATLAB automatically chose the colors for the graphs to be traced with. In

the first method, however, we can enter the color explicitly.

 

>> plot(x,exp(x),'b',x,second,'m',x,third,'g');

 

We can also choose to draw each graph in a different line-style for black and white printing purposes by entering:

 

>> plot(x,exp(x),':',x,second,'--',x,third,'-.');

 

Exercise: Combine different colors with different line-styles.

 

Third method (the hold command)

 

This method is substantially different (and more general) than the first two. It makes use of the command hold, which freezes (holds) the current picture. To defrost (release) the picture use hold again. Example:

 

>> x=-1:.02:1;

 

>> plot(x,exp(x));

 

>> second=1+x+(1/2)*x.^2;third=second+(1/6)*x.^3;

 

>> hold

 

Current plot held

 

>> plot(x,second);plot(x,third);

 

>> hold

 

Current plot released

 

Another example, which illustrates the generality of the hold command, is the following:

 

>> temp_min=[27,25,29,39,48,61,70,77,69,51,44,30];

 

>> bar(temp_max,'r');

 

>> hold

 

Current plot held

 

>> bar(temp_min,'b');hold

 

Current plot released

 

To emphasize the fact that the plots of MATLAB can represent more than mere functions graphs, try the following example of reporting the typical data of a repeated experiment with one parameter.

 

>> data=[

1.2 3.3

1.4 3.5

1.5 3.3

1.7 3.9

1.3 3.4

1.5 3.5

1.8 4.5

1.9 5.4

1.8 4.4

1.9 5.2

1.4 3.6

1.3 3.2

2.2 10.3

1.5 3.7

0.9 3.1

1.7 4.1

1.6 3.5

1.2 3.2

1.9 5.7

1.0 3.2

1.7 3.8

1.4 3.0

1.8 4.9

2.5 13.1

1.6 3.4

];

 

>> plot(data(:,1),data(:,2),'o');

 

Remark: In this example we have used the colon notation data(:,n), which means the n-th column of the matrix data . Analogously, if we were to write M(n,:) for some matrix M and some number n, this would extract the n-th row of M .

 

 

2. Symbolic Computations

 

You might have already heard of software like MATHEMATICA (R) or MAPLE (R). These are the two most widely used examples of symbolic computation software. As opposed to this type of software, MATLAB is a numeric computation software. Nevertheless, MATLAB is able to perform symbolic computations: in fact MATLAB relies on MAPLE (R) in order to perform the symbolic computations.

 

Symbolic computations are those computations that involve symbols (the symbols can be any valid MATLAB variable names). Let us do two examples.

 

A. Creating Symbolic Expressions

 

First we need to declare which will be our symbolic variables.

 

>> syms a b c d x y z

 

then we proceed as if these symbols were actual numbers in floating point notation or MATLAB variables:

 

>> A= [a b; c d]

 

>> A(1)

 

>> det(A)

 

>> eig(A)

 

B. Creating Symbolic Functions

 

We can define a function f symbolically as an expression:

 

>> f = 1 + 2*x^2 + cos(x)

 

We can compute the derivative of f using the command diff:

 

>> diff(f)

 

assign this new expression to another variable:

 

>> f_prime=diff(f)

 

and take successive derivatives:

 

>> f_second=diff(f,2)

 

To find the antiderivative (primitive, or indefinite integral) of f type in:

 

>> int(f)

 

and for the definite integral, between 0 and 2 for example, enter:

 

>> int(f,0,2)

 

C. Solving equations symbolically

 

We can also solve symbolically algebraic equations. For example, consider the quadratic equation:

 

a x2 + b x + c = 0.

 

This can be solved by the following sequence of statements:

 

>> syms x a b c

 

>> p = a*x^2 + b*x + c

 

>> solve(p)

 

Notice that we obtain two solutions in the form of a vector.

 

Remark: If nothing is specified, the symbol x is considered to be the unknown.

 

Example: Consider the equation:

 

ln (y) - ln (r-y) = k t + C

 

where r, k and C are constants, t is a parameter and y is the unknown. To solve for y, type:

 

>> syms r k C t y

 

>> equation = 'log(y) - log(r-y) = k*t + C'

 

>> solve(equation,y)

 

Since the solution is one (unlike the quadratic case), we can solve and assign:

 

>> y = solve(equation,y)

 

Now y is an expression and we can exploit it. If we wish for example, we can solve the equation:

 

y = 5

 

for t:

 

>> solve(y-5,t)

 

E. Solving Differential Equations

 

We can use the function dsolve to solve symbolic differential equations.

 

To solve the following equation:

 

y'=y

 

We need first to make sure y is a symbolic variable:

 

>>sym y

 

Then we use dsolve to solve the equation:

 

>>dsolve('Dy=y')

 

Notice that D is the differential operator (in other words, Dy means the derivative of y). As well, this equation gives a family of solutions, with C1 as the constant.

 

If we want to put initial conditions, we just add them as additional arguments of the function dsolve:

 

>>dsolve('Dy=y', 'y(0)=1')

 

 

3. Exercises

 

Plot the following graphs in the (x,y)-plane:

y = sin (x), for x in [-2 pi, 2 pi];

y = arctan (x), for t in [-10,10];

x = y3 + ey, for x in [-2,7].

 

Enter the following data in a matrix form and then produce a pertinent plot of the data:

height (inches) 62 80 67 72 76 67 73 79 67 69 72 70 64 69 73 71 61

weight (lbs.) 110 180 120 151 160 123 155 158 123 147 166 156 108 152 170 175 103

 

Solve symbolically the equation:

x3-x+1/10=0.

 

 

Part 3: Programming with MATLAB

 

MATLAB is mainly a programming language. The power of MATLAB lies in its flexibility, adaptability and ease in programming. What requires hours of planning and implementing (not to speak of debugging!) in C/C++ or Fortran can be done in minutes with MATLAB.

 

1. The M-files

 

An M-file is the mysterious sounding name for any sequence of MATLAB commands that is stored into a file. There are three general types of M-files that you may find useful. The first is a 'Data M-file'. In it you store the variables, constants, and matrices that you are using during your MATLAB session. The second, which we will discuss here, is called a 'Script M-file'. It stores a series of commands which are executed by MATLAB when you type the filename of the M-file. Storing sequences of commands is handy when the same sequence is to be used many times.

 

Let us focus on a concrete example:

 

We would like to plot the graphs of the functions fn (x) = xn e-nx on the interval [0,20] for all integers n between 1 and 30.

 

We could use plot and hold, but we would have to type in almost the same command line thirty times... Can we do something better? Yes, we are going to edit an m-file that performs the task. To this end we must first open an editor. This can be done from within the MATLAB shell by invoking:

 

>> edit

 

and this should open the MATLAB editor/debugger. Now let us type in the editor buffer the following script:

 

x = 0:.1:20;

plot(x, x.*exp(-x))

hold

for n = 2:10

plot(x, x.^n.*exp(-n*x))

end

hold

 

Save this file as first.m and come back to the MATLAB shell. Finally, enter the command line:

 

>> first

 

NOTICE: You might have problems with this because your path is not set correctly. The path is a collection of directories (folders) where MATLAB goes to look for programs to be run. If you saved that file first in, say, Myfolder, you should tell this to MATLAB by typing:

 

>> cd Myfolder

 

or opening the path browser utility from your MATLAB window.

 

The third type, the function M-file, is by far the most powerful in MATLAB. The M-file will be discussed in the Intermediate Class in some depth, since it is an important aspect of MATLAB.

 

Before we move on to the last topic in our class, letís take a look at one command in particular which may be found useful in script files.

 

 

2. Loops and Conditions: For, While, If Loops

 

A for loop will execute the commands within that loop for each value of the index in the for command. As in the example above, we executed the function for various values of n and then plotted each of those graphs. For loops are a powerful shorthand for doing things that are nearly the same over and over.

 

The next example will illustrate the for-loop used again.

 

 

3. Exercises

 

We will construct a script m-file. The Fibonacci sequence is defined by the recursion:

 

an+1 = an + an-1, for n = 1, 2, ...

 

The first two terms (starting values or seeds) a0 and a1 are usually prescribed numbers.

 

Classically, the Fibonacci sequence starts with:

 

a0 = 1 and a1 = 1.

 

It is a well known fact that:

 

lim an+1/an = (1 + sqrt(5))/2, as n tends to infinity.

 

(The golden ratio.)

 

The following script will compute the 100th term of the Fibonacci ratio sequence:

 

a0 = 1;

a1 = -2;

for n = 2:100

a = a1+a0;

a0 = a1;

a1 = a;

end

a1/a0

 

Remember: you must save this and then run it from the shell by typing in the name of the file you gave it.

 

 

Part 4: Managing MATLAB

 

1. Printing and Exporting

 

We obviously must be able to print the graphical output. There are several ways of doing this. The simplest one consists in using the menubar of the output window: click on File and then on Print...

 

Another way of printing is to use print . To print the current plot just enter print .

 

>> print

 

A plot however can also be print-ed (or exported) to a file. Examples of this are:

 

>> print -dps2 snapshot

 

which will generate a PostScript (*) file named snapshot.ps .

[(*) PostScript (ps) is a standard format for printable graphic objects];

 

>> print -dpsc2 snapshot

 

will generate a color PostScript file;

 

>> print -djpeg snapshot

 

will generate a jpeg (*) file named snapshot.jpg or snapshot.jpeg .

[(*) JPEG (or JPG) is a popular format for pictures that is "understood" by most internet browsers.]

 

 

2. Saving and loading MATLAB sessions

 

We have seen how to save the pictures that are produced by MATLAB. What about saving the results of a computation? It is not rare that one has to save a 1000 by 1000 matrix: i.e., one million numbers! To save the variables that are in use in a session we use save. For example, suppose you want to save all the variables of your session then:

 

>> save sess1

 

will save your data in a file named sess1. If you only want to save certain variables (e.g., A B Q m z) then you just need to list them after the name of the file:

 

>> save sess1 A B Q m z

 

To retrieve these variables in some other session we enter:

 

>> load sess1

 

 

3. Submitting MATLAB work

 

The neater the assignment, the happier the teacher. MATLAB offers an easy way for turning in organized and readable work. Here are some tips.

 

Use the diary command:

 

>> diary results

 

All the input and output of your session will be saved in a file named results.

If there are some parts you don't want to save, then before them type:

 

>> diary off

 

You can switch the diary on again by typing:

 

>> diary on

 

Before turning in the assignment you can (should!) edit the diary file (results, in our example) by inserting your own comments as a text. Use it also to add embellishments in your graphs, write labels, and put information wherever you think it is appropriate.

 

 

PT home | About PT | Schedule | Registration | Courses | Alternatives | Contact us

Direct questions and comments to Carol Warrington.
© 2002 University of Maryland
Last modified Wednesday, April 9th, 2003

 

How are we doing?site map
Office of Information Technology
Office of Information Technology University of Maryland Academic Support