Thursday 1 June 2017

A Beginner’s Guide to MATLAB

1.How to read this tutorial:

In the sections that follow, 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
As we will see, MATLAB is much more than a “fancy” calculator. In order to get the most out
this tutorial you are strongly encouraged to try all the commands introduced in each section and
work on all the recommended exercises. This usually works best if after reading this guide once,
you read it again (and possibly again and again) in front of a computer.

2. MATLAB BASICS

2.1 The basic features:

Let us start with something simple, like defining a row vector with components the numbers 1, 2,
3, 4, 5 and assigning it a variable name, say x.
» x = [1 2 3 4 5]
x =1 2 3 4 5
Note that we used the equal sign for assigning the variable name x to the vector, brackets to
enclose its entries and spaces to separate them. (Just like you would using the linear algebra
notation). We could have used commas ( , ) instead of spaces to separate the entries, or even a
combination of the two. The use of either spaces or commas is essential!
To create a column vector (MATLAB distinguishes between row and column vectors, as it
should) we can either use semicolons ( ; ) to separate the entries, or first define a row vector and
take its transpose to obtain a column vector. Let us demonstrate this by defining a column vector
y with entries 6, 7, 8, 9, 10 using both techniques.
» y = [6;7;8;9;10]
y =
6
7
8
9
10
» y = [6,7,8,9,10]
y =
6 7 8 9 10
» y'
ans =
6
7
8
9
10
Let us make a few comments. First, note that to take the transpose of a vector (or a matrix for
that matter) we use the single quote ( ' ). Also note that MATLAB repeats (after it processes)
what we typed in. Sometimes, however, we might not wish to “see” the output of a specific
command. We can suppress the output by using a semicolon ( ; ) at the end of the command line.
Finally, keep in mind that MATLAB automatically assigns the variable name ans to anything that
has not been assigned a name. In the example above, this means that a new variable has been
created with the column vector entries as its value. The variable ans, however, gets recycled and
every time we type in a command without assigning a variable, ans gets that value.
It is good practice to keep track of what variables are defined and occupy our workspace. Due to
the fact that this can be cumbersome, MATLAB can do it for us. The command whos gives all
sorts of information on what variables are active.
» whos
Name        Size          Elements           Bytes         Density           Complex
ans            5 by 1           5                      40                Full               No
x               1 by 5           5                      40                Full               No
y               1 by 5           5                      40                Full               No
Grand total is 15 elements using 120 bytes.
A similar command, called who, only provides the names of the variables that are active.
» who
Your variables are:
ans   x    y
If we no longer need a particular variable we can “erase” it from memory using the command
clear variable_name. Let us clear the variable ans and check that we indeed did so.
» clear ans
» who
Your variables are:
x    y
The command clear used by itself, “erases” all the variables from the memory. Be careful, as
this is not reversible and you do not have a second chance to change your mind.
You may exit the program using the quit command. When doing so, all variables are lost.
However, invoking the command save filename before exiting, causes all variables to be
written to a binary file called filename.mat. When we start MATLAB again, we may retrieve
the information in this file with the command load filename. We can also create an ascii
(text) file containing the entire MATLAB session if we use the command diary filename at
the beginning and at the end of our session. This will create a text file called filename (with no
extension) that can be edited with any text editor, printed out etc. This file will include everything
we typed into MATLAB during the session (including error messages but excluding plots). We
could also use the command save filename at the end of our session to create the binary file
described above as well as the text file that includes our work.
One last command to mention before we start learning some more interesting things about
MATLAB, is the help command. This provides help for any existing MATLAB command. Let
us try this command on the command who.
» help who
WHO List current variables.
WHO lists the variables in the current workspace.
WHOS lists more information about each variable.
WHO GLOBAL and WHOS GLOBAL list the variables in the
global workspace.
Try using the command help on itself!
On a PC, help is also available from the Window Menus. Sometimes it is easier to look up a
command from the list provided there, instead of using the command line help.

2.2 Vectors and matrices

2.2 Vectors and matrices
We have already seen how to define a vector and assign a variable name to it. Often it is useful to
define vectors (and matrices) that contain equally spaced entries. This can be done 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, 1, 2, 3, …,
7, 8, you can type
» u = [0:8]
u =
0 1 2 3 4 5 6 7 8
Here we specified the first entry 0 and the last entry 8, separated by a colon ( : ). MATLAB
automatically filled-in the (omitted) entries using the (default) increment 1. You could also
specify an increment as is done in the next example.
To obtain a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
» v = [0:2:8]
v =
0 2 4 6 8
Here we specified the first entry 0, the increment value 2, and the last entry 8. The two colons ( :
) “tell” MATLAB to fill in the (omitted) entries using the specified increment value.
MATLAB will allow you to look at specific parts of the vector. If you want, for example, to only
look at the first 3 entries in the vector v, you can use the same notation you used to create the
vector:
» v(1:3)
ans =
0         2              4
Note that we used parentheses, instead of brackets, to refer to the entries of the vector. Since we
omitted the increment value, MATLAB automatically assumes that the increment is 1. The
following command lists the first 4 entries of the vector v, using the increment value 2 :
» v(1:2:4)
ans =
0      4
Defining a matrix is similar to defining a vector. To define a matrix A, you can treat it like a
column of row vectors. That is, you enter each row of the matrix as a row vector (remember to
separate the entries either by commas or spaces) and you separate the rows by semicolons ( ; ).
» A = [1 2 3; 3 4 5; 6 7 8]
A =
1 2 3
3 4 5
6 7 8
We can avoid separating each row with a semicolon if we use a carriage return instead. In other
words, we could have defined A as follows
» A = [
1 2 3
3 4 5
6 7 8]
A =
1 2 3
3 4 5
6 7 8
which is perhaps closer to the way we would have defined A by hand using the linear algebra
notation.
You can refer to a particular entry in a matrix by using parentheses. For example, the number 5
lies in the 2nd row, 3rd column of A, thus
» A(2,3)
ans =
5
The order of rows and columns follows the convention adopted in the linear algebra notation.
This means that A(2,3) refers to the number 5 in the above example and A(3,2) refers to the
number 7, which is in the 3rd row, 2nd column.
Note MATLAB’s response when we ask for the entry in the 4th row, 1st column.
» A(4,1)
??? Index exceeds matrix dimensions.
As expected, we get an error message. Since A is a 3-by-3 matrix, there is no 4th row and
MATLAB realizes that. The error messages that we get fromMATLAB can be quite informative when trying to find out what went wrong. In this case MATLAB told us exactly what the
problem was.
We can “extract” submatrices using a similar notation as above. For example to obtain the
submatrix that consists of the first two rows and last two columns of A we type
» A(1:2,2:3)
ans =
2  3
4  5
We could even extract an entire row or column of a matrix, using the colon ( : ) as follows.
Suppose we want to get the 2nd column of A. We basically want the elements [A(1,2)
A(2,2) A(3,2)]. We type
» A(:,2)
ans =
2
4
7
where the colon was used to tellMATLAB that all the rows are to be used. The same can be
done when we want to extract an entire row, say the 3rd one.
» A(3,:)
ans =
6 7 8
Define now another matrix B, and two vectors s and t that will be used in what follows.
» B = [
-1 3 10
-9 5 25
0 14 2]
B =
-1 3 10
-9 5 25
0 14 2
» s = [-1 8 5]
s =
-1 8 5
» t = [7;0;11]
t =
7
0
11
The real power of MATLAB is the ease in which you can manipulate your vectors and matrices.
For example, to subtract 1 from every entry in the matrix A we type
» A-1
ans =
0 1 2
2 3 4
5 6 7
It is just as easy to add (or subtract) two compatible matrices (i.e. matrices of the same size).
» A+B
ans =
0 5 13
-6 9 30
6 21 10
The same is true for vectors.
» s-t
??? Error using ==> -
Matrix dimensions must agree.
This error was expected, since s has size 1-by-3 and t has size 3-by-1. We will not get an error if
we type
» s-t'
ans =
-8 8 -6
since by taking the transpose of t we make the two vectors compatible.
We must be equally careful when using multiplication.
» B*s
??? Error using ==> *
Inner matrix dimensions must agree.
» B*t
ans =
103
212
22
Another important operation that MATLAB can perform with ease is “matrix division”. If M is
an invertible† square matrix and b is a compatible vector then
x = M\b is the solution of M x = b and
x = b/M is the solution of x M = b.
Let us illustrate the first of the two operations above with M = B and b = t.
» x=B\t
x =
2.4307
0.6801
0.7390
x is the solution of B x = t as can be seen in the multiplication below.
» B*x
ans =
7.0000
0.0000
11.0000
Since x does not consist of integers, it is worth while mentioning here the command format
long. MATLAB only displays four digits beyond the decimal point of a real number unless we
use the command format long, which tells MATLAB to display more digits.
» format long
» x
x =
2.43071593533487
0.68013856812933
0.73903002309469
On a PC the command format long can also be used through the Window Menus.

There are many times when we want to perform an operation to every entry in a vector or matrix.
MATLAB will allow us to do this with “element-wise” operations.
For example, suppose you want to multiply each entry in the vector s with itself. In other words,
suppose you want to obtain the vector s2 = [s(1)*s(1), s(2)*s(2), s(3)*s(3)].
The command s*s will not work due to incompatibility. What is needed here is to tellMATLAB
to perform the multiplication element-wise. This is done with the symbols ".*". In fact, you can
put a period in front of most operators to tellMATLAB that you want the operation to take place
on each entry of the vector (or matrix).
» s*s
??? Error using ==> *
Inner matrix dimensions must agree.
» s.*s
ans =
1 64 25
The symbol " .^ " can also be used since we are after all raising s to a power. (The period is
needed here as well.)
» s.^2
ans =
1        64          25

The table below summarizes the operators that are available in MATLAB

  • +                addition
  • -                 subtraction
  • *                multiplication
  • ^                power
  • '                 transpose
  • \                 left division
  • /                 right division

Remember that the multiplication, power and division operators can be used in conjunction with a
period to specify an element-wise operation.



0 comments:

Post a Comment