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