Introduction to Matlab
(A
Matlab Tutorial)
1.1 Introduction
Matlab is a high-performance
language for technical computing. Matlab is becoming increasingly popular among
students, researchers and engineers because it integrates computation,
visualization, and programming in an easy-to-use environment where problems and
solutions are expressed in familiar mathematical notation.
The Matlab package provides
a family of application specific solutions called toolboxes. Toolboxes
are collections of Matlab functions that extend the Matlab environment to solve
particular classes of problems.
This tutorial section of the
book is intended to help you start learning Matlab before proceeding with the
“signals and systems” projects that will follow.
1.2 Starting Matlab
Assuming that you
already have an installation of Matlab in your computer, click on the Matlab
icon to start it and the Matlab command window open up. This is the primary
place where you interact with Matlab. After some messages, the Matlab prompt “»”
will appear in the command window to indicate that Matlab is ready to serve you,
i.e. it is waiting for you to enter a command.
This section describes the
basic features of the Matlab command window and a few ways of altering them.
2.1 The Matlab Workspace
As you
work in the command window, Matlab remembers the commands you enter as well as
the values of any variables you create. These commands and the variables can be
called whenever you wish. For example, first create a variable, let us say x,
and assign a value to it. (Needless to say, you should hit “Enter” (¿)
key after completing each one of your command lines, to have Matlab process
them.)
» x=5
x =
5
To
check the value of x all you have to do is ask Matlab for it by entering its
name at the prompt.
» x
x =
5
If you
forget the name of a variable, you can ask Matlab for a list of variables in the
Workspace by using the Matlab command who.
» who
Your variables are:
x
Maybe a
more useful command is the whos command, which is a long form of who, that lists
all the variables in the current workspace, along with information about their
sizes. Note, however, that who or whos commands only lists your variables, they
will not tell you the values of your variables. To learn their values, you must
enter their names at the Matlab prompt.
NOTE: Matlab is a
case-sensitive language, i.e. whether you use upper or lower case letters does
matter. Therefore, x and X are treated as different variables. Try, for
instance, typing COS(pi) and cos(pi) at the Matlab prompt and see what happens.
2.2
Number Display Formats
The
format command controls the format of the numbers displayed by Matlab. Default
output display format of Matlab is “short”. Here is how a number looks under
different output formats.
» format short
» x=5/3
x =
1.6667
» format short e
» x
x =
1.6667e+000
» format long
» x
x =
1.66666666666667
» format rat
» x
x =
5/3
NOTE: Matlab does all of its
computations in double precision. The format command does not change internal
representation of numbers, it only changes the way they are displayed.
2.3
Suppressing Output
When
you type a statement and press Enter, if that statement is producing numerical
results, Matlab automatically displays the result in the command window.
» x=5/3
x =
1.6667
However, if you end the statement with a semicolon “;” Matlab performs the
computation and/or assignment but does not display the result.
» x=5/3;
»
This feature is especially
useful when you do not want to see results of assignments or computations that
involve some large vector or matrix variables, because it may take too long to
display them in the command window.
2.4
Command Window Control
Matlab
has several commands to let us manage the command window.
|
clc |
Clear the Command
window |
|
diary |
Save Command window
text to a file |
|
more |
Page the Command
window |
Using
the diary feature of Matlab you can keep a record of our activities in a Matlab
session. Issuing diary
filename
causes a copy of all subsequent command window input and resulting output to be
written into the file filename, diary off suspends it, diary on turns it
back on, and diary, by itself, toggles the diary state.
2.5
Command Line Editing
Various
arrows and control keys on your keyboard allow you to recall, edit, and reuse
commands you have typed earlier.
|
|
|
|
¯ |
Recall next line |
|
® |
Move forward one character |
|
¬ |
Move back one character |
|
Esc |
Clear line |
|
Del |
Delete character at cursor |
|
Backspace |
Delete character before cursor |
|
Ctrl-A |
Go to beginning of command line |
|
Ctrl-E |
Go to end of command line |
2.6
Comments and Punctuations
All text after a percent
sing (%) till to the end of line is taken as a comment statement and ignored by
Matlab. This feature makes it easy to document what you are doing.
» x=5;
» y=3;
» x*5/y % Multiply x by 5
then divide by y
ans =
25/3
Multiple commands can be placed on one line if commas or semicolons separate
them.
» x=5; y=4, z=x*y;
y =
4
3.1
Arithmetic Operations
Expressions in Matlab use familiar arithmetic operators and precedence rules.
+
Addition
–
Subtraction
*
Multiplication
/
Right division
\
Left division
^
Power
' Complex conjugate transpose
() Parenthesis (Specifies evaluation order)
Here
are some examples.
» 2+3
ans =
5
» 5*6+3
ans =
33
» 2^(3+1) % 4th
power of 2
ans =
16
3.2
Variables
In
previous sections, you have already learned how to create a new variable and
assign a value to it. When Matlab encounters a new variable name on the left
hand side of an assignment statement, it automatically creates that variable and
allocates the appropriate storage for it. If the variable already exists, Matlab
may change its contents, depending on the statement.
You
also can do arithmetic operations by directly using variable names.
» alpha=90;
» beta=45;
» teta=alpha+beta
teta =
135
3.3
Mathematical Functions
Matlab provides a large
number of built-in standard elementary mathematical functions. Most of these
functions are used the same way you would write them mathematically.
» x=sqrt(2)
x =
1.4142
» y=sin(x)
y =
0.9878
» round(y)
ans =
1
For a
list of elementary mathematical functions type help elfun at the Matlab prompt.
Also see the Matlab Reference Guide, which must be available in pdf
format somewhere in your Matlab directory, for more information about these
functions.
4.1
One-dimensional Arrays
In
other programming languages, when one wishes to perform the same mathematical
operation on more than one number, repeated scalar operations are performed. To
solve this problem Matlab defines operations on data-arrays or vectors.
An
ordered collection of numbers, a1, a2, a3
…., an can be defined in Matlab as an array. For an
example, you can create the array of first 6 natural numbers named nat_numbers
either as,
» nat_numbers=[1 2 3 4 5 6]
nat_numbers =
1 2 3 4
5 6
» nat_numbers=[1,2,3,4,5,6]
nat_numbers =
1 2 3 4
5 6
As you see above, blanks or
commas can separate elements of arrays. You can reach elements of an array by
using the corresponding indices.
» nat_numbers(2)
ans =
2
» nat_numbers(6)
ans =
6
The
addition and subtraction operations are defined between arrays of the same
length. As an example, let us define three arrays of four elements and do
addition and subtraction operations on them.
» A=[1 3 5 7];
» B=[2 4 6 8];
» C=[3 6 9 12];
» D=A+B-C
D =
0 1 2 3
It is
also possible to enter or to change the elements of an array using their index
values.
» A=[1 3 5 7]
A =
1 3 5 7
» A(3)=25
A =
1 3 25 7
» A(1)=A(2)-A(4)
A =
-4 3 25 7
4.2
More Operations on Arrays
In the
previous section, you entered the values of nat_numbers by typing each
individual element in nat_numbers. While this is fine when there are only 6
values in nat_numbers, but what if there are 500 values? In Matlab, arrays of
equally spaced elements can be created by using the colon notation,
start:increment:end, where starting or the first element, the increment, and the
last element separated by colons are given.
» nat_numbers=1:1:9
nat_numbers =
1 2 3 4
5 6 7 8 9
» x=(0:0.1:1)*pi %An example
of scalar-array operation
x =
Columns 1 through 7
0 0.3142
0.6283 0.9425 1.2566 1.5708 1.8850
Columns 8 through 11
2.1991 2.5133
2.8274 3.1416
In the
second example above, the colon notation (0:0.1:1) creates an array that starts
at 0, increments by 0.1, and ends at 1. Then each element in this array is
multiplied by p
to create the desired values in x.
It is also possible to
create an array composed of two or more arrays.
» A=[1 2 3];
» B=4:7
B =
4 5 6 7
» C=[A B]
C =
1 2 3 4
5 6 7
When two arrays have the
same size, you may have multiplication and division apply on an element by
element basis in Matlab, by preceding them with a dot.
» A
A =
1 2 3
» B
B =
4 5 6
» A.*B %Elementwise
multiplication of two same size arrays
ans =
4 10 18
» A./B
ans =
0.2500 0.4000
0.5000
Similarly, you can raise the elements of an array to the same power by using the
power operator with a dot in front,“.^”. For example, the squares of the first
six natural numbers can be calculated as follows.
» nat_numbers.^2
ans =
1 4 9 16
25 36
Most of
the Matlab functions can also be applied to arrays, simply by calling them with
array arguments. The function will operate on all array elements as if called
for each element individually. As an example, let us calculate the cosine of the
angles 0, 10, 20, ..., 90 degrees.
» angle=0:10:90;
» angle = pi*angle/180; %
Convert degrees to radians
» cos(angle)
ans =
Columns 1 through 7
1.0000 0.9848
0.9397 0.8660 0.7660 0.6428 0.5000
Columns 8 through 10
0.3420 0.1736
0.0000
4.3
Matrices
Two-dimensional arrays or
matrices are collections of numbers identified by two indices. Matrices can be
entered in a way similar to entering one-dimensional arrays. You can write all
rows in one line and use a semicolon, ; to indicate the end of each row,
» A=[1 2 3;4 5 6;7 8 9]
A =
1 2 3
4 5 6
7 8 9
or you can write each row
separately in a line and by pressing Enter after rows.
» A=[1 2 3
4 5 6
7 8 9]
A =
1 2 3
4 5 6
7 8 9
You can
reach any element of a matrix by using its two indices, row and column.
» A(2,1)
ans =
4
If you
try to reach outside a matrix’s row and column limits, you will get an error
message indicating the problem.
» A(5,4)
??? Index exceeds matrix
dimensions.
You can
retrieve the number of rows and columns of a matrix, i.e. its size, by using the
size function.
size(A)
ans =
3 3
The colon operator, : is one
of the most important operators of Matlab. You remember that we used it to
create linearly spaced arrays. We can also use the colon operator to refer to
portions of a matrix. For instance, here is how to retrieve the first 2 elements
of the second column of A,
» A(1:2,2)
ans =
2
5
and how to assign the first
row of A to a new array X.
» X=A(1,:)
X =
1 2 3
4.4
Special Matrices
Matlab
offers a number of built-in functions that create special matrices such as
zeros, ones and eye.
» B=zeros(3) %A 3 by 3 matrix
of zeros
B =
0 0 0
0 0 0
0 0 0
» C=ones(2,3) %A 2 by 3
matrix of ones
C =
1 1 1
1 1 1
magic(n)
creates an n by n matrix from the integers 1 through n2 with equal
row, column, and diagonal sums.
» magic(3)
ans =
8 1 6
3 5 7
4 9 2
rand(n,m) creates an n by m matrix of uniformly distributed random numbers
between 0 and 1.
» rand(2,3)
ans =
0.9501 0.6068
0.8913
0.2311 0.4860
0.7621
eye(n)
creates an n by n identity matrix.
» eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
4.5
Matrix Functions
Matlab
offers a broad range of matrix functions covering almost all aspects of linear
algebra. We will just mention a few of them here.
det is
used to find the determinant of a square matrix.
» det(magic(3)) % Note the
nested call of functions
ans =
-360
'
operator is used to transpose vectors or matrices.
» A =[1 2 3;4 5 6]
A =
1 2 3
4 5 6
» A'
ans =
1 4
2 5
3 6
inv
finds the inverse of a square matrix.
» inv(magic(3))
ans =
0.1472 -0.1444
0.0639
-0.0611 0.0222
0.1056
-0.0194 0.1889
-0.1028
rank
function finds the number of linearly independent rows or columns of a matrix,
whichever is smaller.
» rank(magic(3))
ans =
3
4.6
Scalar – Matrix Operations
Addition, subtraction,
multiplication or division by a scalar, simply apply the operation to all
elements of the matrix. For instance, here is how to create a 3 by 3 matrix with
all elements equal to
p.
» X=ones(3)*pi
X =
3.1416 3.1416
3.1416
3.1416 3.1416
3.1416
3.1416 3.1416
3.1416
4.7
Matrix – Matrix Operations
Addition and subtraction can be done among matrices of the same size.
» A=[1 3;4 6;8 9];
» B=round(rand(3,2)*100)
B =
68 15
30 70
54 38
» C=ones(3,2)*5
C =
5 5
5 5
5 5
» D=A-B+C
D =
-62 -7
-21 -59
-41 -24
Using
regular matrix multiplication, two conforming matrices, an n by m matrix and an
m by p matrix can be multiplied, yielding an n by p matrix.
» A=[2 3 4;4 0 1];
» B=[2 4 6]'; % ’takes the
transpose of a matrix.
» A*B
ans =
40
14
When two arrays have the
same dimensions, multiplication and division can also be done on an element by
element basis in Matlab.
» A=[1 2 3;4 5 6];
» B=[2 4 6;0 0 1];
» A.*B % Elementwise
multiplication via .* operator
ans =
2 8 18
0 0 6
» B./A % Elementwise
multiplication via ./ operator
ans =
2.0000 2.0000
2.0000
0 0 0.1667