Chapter 3 INTRODUCTION TO MATLAB

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Chapter 3: INTRODUCTION TO MATLAB

MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software


package, which is used extensively in both academia and industry. It is an interactive program
for numerical computation and data visualization, which along with its programming capabilities
provides a very useful tool for almost all areas of science and engineering. Unlike other
mathematical packages, such as MAPLE or MATHEMATICA, MATLAB cannot perform
symbolic manipulations without the use of additional Toolboxes. It remains however, one of the
leading software packages for numerical computation.
As you might guess from its name, MATLAB deals mainly with matrices. A scalar is a 1-by-1
matrix and a row vector of length say 5, is a 1-by-5 matrix. One of the many advantages of
MATLAB is the natural notation used. It looks a lot like the notation that you encounter in a
linear algebra course. This makes the use of the program especially easy and it is what makes
MATLAB a natural choice for numerical computations.
The MATLAB prompt (») will be used to indicate where the commands are entered. Anything
you see after this prompt denotes user input (i.e. a command) followed by a carriage return (i.e.
the “enter” key). Often, input is followed by output so unless otherwise specified the line(s) that
follow a command will denote output (i.e. MATLAB’s response to what you typed in).
MATLAB is case-sensitive, which means that a + B is not the same as a + b. Different fonts, like
the ones you just witnessed, will also be used to simulate the interactive session. This can be
seen in the example below:
e.g. MATLAB can work as a calculator. If we ask MATLAB to add two numbers, we get the
answer we expect.
»3+4
ans =
7
The Command Window
You can start MATLAB by double clicking on the MATLAB icon that should be on the desktop
of your computer. This brings up the window called the Command Window. This window
allows a user to enter simple commands. To clear the Command Window type clc and next
press the Enter or Return key. To perform a simple computations type a command and next
press the
Enter or Return key. For instance,
s=1+2
s=
3
fun = sin(pi/4)
fun =
0.7071
In the second example the trigonometric function sine and the constant _ are used. In MATLAB
they are named sin and pi, respectively.
Note that the results of these computations are saved in variables whose names are chosen by the
user. If they will be needed during your current MATLAB session, then you can obtain their
values typing their names and pressing the Enter or Return key. For instance,
s
s=
3
Variable name begins with a letter, followed by letters, numbers or underscores. MATLAB
recognizes only the first 31 characters of a variable name.
To change a format of numbers displayed in the Command Window you can use one of the
several formats that are available in MATLAB. The default format is called short (four digits
after the decimal point.) In order to display more digits click on File, select Preferences…, and
next select a format you wish to use. They are listed below the Numeric Format. Next click on
Apply and OK and close the current window. You can also select a new format from within the
Command Window. For instance, the following command
format long
changes a current format to the format long. To display more digits of the variable fun type
fun
fun =
0.70710678118655
To change a current format to the default one type
format short
fun
fun =
0.7071
To close MATLAB type exit in the Command Window and next press Enter or Return key. A
second way to close your current MATLAB session is to select File in the MATLAB's toolbar
and next click on Exit MATLAB option. All unsaved information residing in the MATLAB
Workspace will be lost.

Introduction to Vectors in Matlab

Defining a Vector

Matlab is a software package that makes it easier for you to enter matrices and vectors, and
manipulate them. The interface follows a language that is designed to look a lot like the notation
use in linear algebra.

Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by
placing a sequence of numbers within square braces:

>> v = [3 1]

v=

3 1

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the
second entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key.
If you do not want to print out the result put a semi-colon at the end of the line:

>> v = [3 1];
>>

If you want to view the vector just type its label:

>> v

v=

3 1
You can define a vector of any size in this manner:

>> v = [3 1 7 -21 5 6]

v=

3 1 7 -21 5 6

Notice, though, that this always creates a row vector. If you want to create a column vector you
need to take the transpose of a row vector. The transpose is defined using an apostrophe ('):

>> v = [3 1 7 -21 5 6]'

v=

3
1
7
-21
5
6

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can
define a set of numbers with a common increment using colons. For example, to define a vector
whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:

>> v = [1:8]
v=

1 2 3 4 5 6 7 8

If you wish to use an increment other than one that you have to define the start number, the value
of the increment, and the last number. For example, to define a vector that starts with 2 and ends
in 4 with steps of .25 you enter the following:

>> v = [2:.25:4]

v=

Columns 1 through 7

2.0000 2.2500 2.5000 2.7500 3.0000 3.2500 3.5000

Columns 8 through 9
3.7500 4.0000

Accessing elements within a vector

You can view individual entries in this vector. For example to view the first entry just type in the
following:

>> v(1)

ans =

This command prints out entry 1 in the vector. Also notice that a new variable called ans has
been created. Any time you perform an action that does not include an assignment matlab will
put the label ans on the result.

To simplify the creation of large vectors, you can define a vector by specifying the first entry, an
increment, and the last entry. Matlab will automatically figure out how many entries you need
and their values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type
in the following line:

>> 0:2:8

ans =

0 2 4 6 8

Matlab also keeps track of the last result. In the previous example, a variable "ans" is created. To
look at the transpose of the previous result, enter the following:
>> ans'

ans =

0
2
4
6
8

To be able to keep track of the vectors you create, you can give them names. For example, a row
vector v can be created:
>> v = [0:2:8]

v=
0 2 4 6 8

>> v

v=

0 2 4 6 8

>> v;
>> v'

ans =

0
2
4
6
8

Note that in the previous example, if you end the line with a semi-colon, the result is not
displayed. This will come in handy later when you want to use Matlab to work with very large
systems of equations.

Matlab will allow you to look at specific parts of the vector. If you want to only look at the first
three entries in a vector you can use the same notation you used to create the vector:

>> v(1:3)

ans =

0 2 4

>> v(1:2:4)

ans =

0 4

>> v(1:2:4)'

ans =

0
4
Basic operations on vectors

Once you master the notation you are free to perform other operations:

>> v(1:3)-v(2:4)

ans =

-2 -2 -2

For the most part Matlab follows the standard notation used in linear algebra. We will see later
that there are some extensions to make some operations easier. For now, though, both addition
subtraction are defined in the standard way. For example, to define a new vector with the
numbers from 0 to -4 in steps of -1 we do the following:

>> u = [0:-1:4]
u = [0:-1:-4]

u=
0 -1 -2 -3 -4

We can now add u and v together in the standard way:

>> u+v

ans =

0 1 2 3 4

Additionally, scalar multiplication is defined in the standard way. Also note that scalar division
is defined in a way that is consistent with scalar multiplication:

>> -2*u

ans =
0 2 4 6 8

>> v/3

ans =

0 0.6667 1.3333 2.0000 2.6667


With these definitions linear combinations of vectors can be easily defined and the basic
operations combined:

>> -2*u+v/3

ans =

0 2.6667 5.3333 8.0000 10.6667

You will need to be careful. These operations can only be carried out when the dimensions of the
vectors allow it. You will likely get used to seeing the following error message which follows
from adding two vectors whose dimensions are different:

>> u+v'
??? Error using ==> plus
Matrix dimensions must agree.

Introduction to Matrices in Matlab

Defining Matrices

Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a
column of row vectors (note that the spaces are required!):

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

A=
1 2 3
3 4 5
6 7 8

You can also treat it like a row of column vectors:

>> B = [ [1 2 3]' [2 4 7]' [3 5 8]']

B=
1 2 3
2 4 5
3 7 8

(Again, it is important to include the spaces.)


As mentioned before, the notation used by Matlab is the standard linear algebra notation. Matrix-
vector multiplication can be easily done. You have to be careful, though, your matrices and
vectors have to have the right size!

>> v = [0:2:8]

v=

0 2 4 6 8

>> A*v(1:3)
??? Error using ==> *
Inner matrix dimensions must agree.

>> A*v(1:3)'

ans =

16
28
46

Get used to seeing that particular error message! Once you start throwing matrices and vectors
around, it is easy to forget the sizes of the things you have created.

You can work with different parts of a matrix, just as you can with vectors. Again, you have to
be careful to make sure that the operation is legal.

>> A(1:2,3:4)
??? Index exceeds matrix dimensions.

>> A(1:2,2:3)

ans =

2 3
4 5

>> A(1:2,2:3)'

ans =

2 4
3 5
Matrix Functions

Once you are able to create and manipulate a matrix, you can perform many standard operations
on it. For example, you can find the inverse of a matrix. You must be careful, however, since the
operations are numerical manipulations done on digital computers. In the example, the matrix A
is not a full matrix, but matlab's inverse routine will still return a matrix.

>> inv(A)

Warning: Matrix is close to singular or badly scaled.


Results may be inaccurate. RCOND = 4.565062e-18

ans =
1.0e+15 *

-2.7022 4.5036 -1.8014


5.4043 -9.0072 3.6029
-2.7022 4.5036 -1.8014

By the way, Matlab is case sensitive. This is another potential source of problems when you start
building complicated algorithms.

>> inv(a)
??? Undefined function or variable a.

Other operations include finding an approximation to the eigen values of a matrix. There are two
versions of this routine, one just finds the eigen values, the other finds both the eigen values and
the eigen vectors. If you forget which one is which, you can get more information by typing help
eig at the matlab prompt.

>> eig(A)

ans =

14.0664
-1.0664
0.0000

>> [v,e] = eig(A)

v=

-0.2656 0.7444 -0.4082


-0.4912 0.1907 0.8165
-0.8295 -0.6399 -0.4082
e=

14.0664 0 0
0 -1.0664 0
0 0 0.0000
>> diag(e)

ans =

14.0664
-1.0664
0.0000
Matrix Operations

There are also routines that let you find solutions to equations. For example, if Ax=b and you
want to find x, a slow way to find x is to simply invert A and perform a left multiply on both
sides (more on that later). It turns out that there are more efficient and more stable methods to do
this (L/U decomposition with pivoting, for example). Matlab has special commands that will do
this for you.

Before finding the approximations to linear systems, it is important to remember that if A and B
are both matrices, then AB is not necessarily equal to BA. To distinguish the difference between
solving systems that have a right or left multiply, Matlab uses two different operators, "/" and "\".
Examples of their use are given below. It is left as an exercise for you to figure out which one is
doing what.

>> v = [1 3 5]'

v=

1
3
5

>> x = A\v

Warning: Matrix is close to singular or badly scaled.


Results may be inaccurate. RCOND = 4.565062e-18
x=
1.0e+15 *

1.8014
-3.6029
1.8014

>> x = B\v
x=

2
1
-1

>> B*x

ans =

1
3
5

>> x1 = v'/B

x1 =

4.0000 -3.0000 1.0000

>> x1*B

ans =

1.0000 3.0000 5.0000

Finally, sometimes you would like to clear all of your data and start over. You do this with the
"clear" command. Be careful though, it does not ask you for a second opinion and its results are
final.

>> clear

>> whos

Vector Functions

Matlab makes it easy to create vectors and matrices. The real power of Matlab is the ease in
which you can manipulate your vectors and matrices.

Here we will first demonstrate simple manipulations such as addition, subtraction, and
multiplication. Following this basic "element-wise" operations are discussed. Once these
operations are shown, they are put together to demonstrate how relatively complex operations
can be defined with little effort.

First, we will look at simple addition and subtraction of vectors. The notation is the same as
found in most linear algebra texts. We will define two vectors and add and subtract them:

>> v = [1 2 3]'

v=

1
2
3

>> b = [2 4 6]'

b=

2
4
6

>> v+b

ans =

3
6
9

>> v-b

ans =

-1
-2
-3

Multiplication of vectors and matrices must follow strict rules. Actually, so must addition. In the
example above, the vectors are both column vectors with three entries. You cannot add a row
vector to a column vector. Multiplication, though, can be a bit trickier. The number of columns
of the thing on the left must be equal to the number of rows of the thing on the right of the
multiplication symbol:

>> v*b
??? Error using ==> *
Inner matrix dimensions must agree.

>> v*b'

ans =

2 4 6
4 8 12
6 12 18

>> v'*b

ans =

28

There are many times where we want to do an operation to every entry in a vector or matrix.
Matlab will allow you to do this with "element-wise" operations. For example, suppose you want
to multiply each entry in vector v with its cooresponding entry in vector b. In other words,
suppose you want to find v(1)*b(1), v(2)*b(2), and v(3)*b(3). It would be nice to use the "*"
symbol since you are doing some sort of multiplication, but since it already has a definition, we
have to come up with something else. The programmers who came up with Matlab decided to
use the symbols ".*" to do this. In fact, you can put a period in front of any math symbol to tell
Matlab that you want the operation to take place on each entry of the vector.

>> v.*b

ans =

2
8
18

>> v./b

ans =

0.5000
0.5000
0.5000

Since we have opened the door to non-linear operations, why not go all the way? If you pass a
vector to a predefined math function, it will return a vector of the same size, and each entry is
found by performing the specified operation on the cooresponding entry of the original vector:
>> sin(v)

ans =

0.8415
0.9093
0.1411

>> log(v)

ans =

0
0.6931
1.0986

The ability to work with these vector functions is one of the advantages of Matlab. Now complex
operations can be defined that can be done quickly and easily. In the following example a very
large vector is defined and can be easily manipulated. (Notice that the second command has a ";"
at the end of the line. This tells Matlab that it should not print out the result.)

>> x = [0:0.1:100]

x=

Columns 1 through 7

0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000

[stuff deleted]

Columns 995 through 1001

99.4000 99.5000 99.6000 99.7000 99.8000 99.9000 100.0000

>> y = sin(x).*x./(1+cos(x));

Through this simple manipulation of vectors, Matlab will also let you graph the results. The
following example also demonstrates one of the most useful commands in Matlab, the "help"
command.

>> plot(x,y)
>> plot(x,y,'rx')
>> help plot

PLOT Linear plot.


PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.

PLOT(Y) plots the columns of Y versus their index.


If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:

b blue . point - solid


g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus


at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by


the (X,Y,S) triples, where the X's and Y's are vectors or matrices
and the S's are strings.

For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a


solid yellow line interpolating green circles at the data points.

The PLOT command, if no color is specified, makes automatic use of


the colors specified by the axes ColorOrder property. The default
ColorOrder is listed in the table above for color systems where the
default is blue for one line, and for multiple lines, to cycle
through the first six colors in the table. For monochrome systems,
PLOT cycles over the axes LineStyleOrder property.
PLOT returns a column vector of handles to LINE objects, one
handle per line.

The X,Y pairs, or X,Y,S triples, can be followed by


parameter/value pairs to specify additional properties
of the lines.

See also SEMILOGX, SEMILOGY, LOGLOG, PLOTYY, GRID, CLF, CLC, TITLE,
XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT, STEM.

Overloaded methods
help idmodel/plot.m
help iddata/plot.m

>> plot(x,y,'y',x,y,'go')
>> plot(x,y,'y',x,y,'go',x,exp(x+1),'m--')
>> whos
Name Size Bytes Class

ans 3x1 24 double array


b 3x1 24 double array
v 3x1 24 double array
x 1x1001 8008 double array
y 1x1001 8008 double array

Grand total is 2011 elements using 16088 bytes

The compact notation will let you tell the computer to do lots of calculations using few
commands. For example, suppose you want to calculate the divided differences for a given
equation. Once you have the grid points and the values of the function at those grid points,
building a divided difference table is simple:

>> coef = zeros(1,1001);


>> coef(1) = y(1);
>> y = (y(2:1001)-y(1:1000))./(x(2:1001)-x(1:1000));
>> whos
Name Size Bytes Class

ans 3x1 24 double array


b 3x1 24 double array
coef 1x1001 8008 double array
v 3x1 24 double array
x 1x1001 8008 double array
y 1x1000 8000 double array
Grand total is 3008 elements using 24064 bytes

>> coef(2) = y(1);


>> y(1)

ans =

0.0500

>> y = (y(2:1000)-y(1:999))./(x(3:1001)-x(1:999));
>> coef(3) = y(1);
>>
>>

From this algorithm you can find the Lagrange polynomial that interpolates the points you
defined above (vector x). Of course, with so many points, this might get a bit tedious.
Fortunately, matlab has an easy way of letting the computer do the repetitive things, which is
examined in the next tutorial.

Loops

For Loops

The for loop allows us to repeat certain commands. If you want to repeat some action in a
predetermined way, you can use the for loop. All of the loop structures in matlab are started with
a keyword such as "for", or "while" and they all end with the word "end". Another deep thought,
eh.

The for loop is written around some set of statements, and you must tell Matlab where to start
and where to end. Basically, you give a vector in the "for" statement, and Matlab will loop
through for each value in the vector:

For example, a simple loop will go around four times each time changing a loop variable, j:

>> for j=1:4,


j
end
j=

j=

j=

j=

>>

When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value
within the vector in order. Once Matlab reads the "end" statement, it will execute and repeat the
loop. Each time the for statement will update the value of j and repeat the statements within the
loop. In this example it will print out the value of j each time.

For another example, we define a vector and later change the entries. Here we step though and
change each individual entry:

>> v = [1:3:10]

v=

1 4 7 10

>> for j=1:4,


v(j) = j;
end
>> v

v=

1 2 3 4
Note, that this is a simple example and is a nice demonstration to show you how a for loop
works. However, DO NOT DO THIS IN PRACTICE!!!! Matlab is an interpreted language and
looping through a vector like this is the slowest possible way to change a vector. The notation
used in the first statement is much faster than the loop.

A better example, is one in which we want to perform operations on the rows of a matrix. If you
want to start at the second row of a matrix and subtract the previous row of the matrix and then
repeat this operation on the following rows, a for loop can do this in short order:

>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']

A=

1 3 2
2 2 1
3 1 3

>> B = A;
>> for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
end

A=

1 3 2
1 -1 -1
3 1 3

A=

1 3 2
1 -1 -1
2 2 4

For a more realistic example, since we can now use loops and perform row operations on a
matrix, Gaussian Elimination can be performed using only two loops and one statement:

>> for j=2:3,


for i=j:3,
B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
end
end
B=

1 3 2
0 -4 -3
3 1 3

B=

1 3 2
0 -4 -3
0 -8 -3

B=

1 3 2
0 -4 -3
0 0 3

Another example where loops come in handy is the approximation of differential equations. The
following example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the
step size, h, is defined. Once done, the grid points are found, and an approximation is found. The
approximation is simply a vector, y, in which the entry y(j) is the approximation at x(j).

>> h = 0.1;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> size(x)

ans =

1 21

>> for i=2:21,


y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
end
>> plot(x,y)
>> plot(x,y,'go')
>> plot(x,y,'go',x,y)
While Loops

If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of
commands as long as some condition is met. This can make for a more efficient algorithm. In the
previous example the number of time steps to make may be much larger than 20. In such a case
the for loop can use up a lot of memory just creating the vector used for the index. A better way
of implementing the algorithm is to repeat the same operations but only as long as the number of
steps taken is below some threshold. In this example the D.E. y'=x-|y|, y(0)=1, is approximated
using Euler's Method:

>> h = 0.001;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> i = 1;
>> size(x)

ans =

1 2001

>> max(size(x))

ans =

2001

>> while(i<max(size(x)))
y(i+1) = y(i) + h*(x(i)-abs(y(i)));
i = i + 1;
end
>> plot(x,y,'go')
>> plot(x,y)

Plotting

Here we will introduce the basic operations for creating plots. To show how the plot command is
used, an approximation using Euler's Method is found and the results plotted. We will
approximate the solution to the D.E. y'= 1/y, y(0)=1. A step size of h=1/16 is specified and
Euler's Method is used. Once done, the true solution is specified so that we can compare the
approximation with the true value. (This example comes from the tutorial on loops.)
>> h = 1/16;
>> x = 0:h:1;
>> y = 0*x;
>> size(y)

ans =

1 17

>> max(size(y))

ans =

17

>> y(1) = 1;
>> for i=2:max(size(y)),
y(i) = y(i-1) + h/y(i-1);
end
>> true = sqrt(2*x+1);

Now, we have an approximation and the true solution. To compare the two, the true solution is
plotted with the approximation plotted at the grid points as a green 'o'. The plot command is used
to generate plots in matlab. There is a wide variety of arguments that it will accept. Here we just
want one plot, so we give it the range, the domain, and the format.

>> plot(x,y,'go',x,true)

That's nice, but it would also be nice to plot the error:

>> plot(x,abs(true-y),'mx')

Okay, let's print everything on one plot. To do this, you have to tell matlab that you want two
plots in the picture. This is done with the subplot command. Matlab can treat the window as an
array of plots. Here we will have one row and two columns giving us two plots. In plot #1 the
function is plotted, while in plot #2 the error is plotted.

>> subplot(1,2,1);
>> plot(x,y,'go',x,true)
>> subplot(1,2,2);
>> plot(x,abs(true-y),'mx')
Figure 1. The two plots from the first approximation

Let's start over. A new approximation is found by cutting the step size in half. But first, the
picture is completely cleared and reset using the clf comand. (Note that I am using new vectors
x1 and y1.)

>> clf
>> h = h/2;
>> x1 = 0:h:1;
>> y1 = 0*x1;
>> y1(1) = 1;
>> for i=2:max(size(y1)),
y1(i) = y1(i-1) + h/y1(i-1);
end
>> true1 = sqrt(2*x1+1);

The new approximation is plotted, but be careful! The vectors passed to plot have to match. The
labels are given for the axis and a title is given to each plot in the following example. The
following example was chosen to show how you can use the subplot command to cycle through
the plots at any time.

>> plot(x,y1,'go',x,true1)
??? Error using ==> plot
Vectors must be the same lengths.
>> plot(x1,y1,'go',x1,true1)
>> plot(x1,abs(true1-y1),'mx')
>> subplot(1,2,1);
>> plot(x,abs(true-y),'mx')
>> subplot(1,2,2);
>> plot(x1,abs(true1-y1),'mx')
>> title('Errors for h=1/32')
>> xlabel('x');
>> ylabel('|Error|');
>> subplot(1,2,1);
>> xlabel('x');
>> ylabel('|Error|');
>> title('Errors for h=1/16')

Figure 2. The errors for the two approximations

Finally, if you want to print the plot, you must first print the plot to a file. To print a postscript
file of the current plot you can use the print command. The following example creates a
postscript file called error.ps which resides in the current directory. This new file (error.ps) can
be printed from the UNIX prompt using the lpr command.

>> print -dps error.ps

You might also like