Introduction To MATLAB: Department of Electrical Engineering, Information Technology and Cybernetics
Introduction To MATLAB: Department of Electrical Engineering, Information Technology and Cybernetics
Introduction to MATLAB
HANS-PETTER HALVORSEN, 2011.06.06
Faculty of Technology, Postboks 203, Kjlnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
Preface
MATLAB is a tool for technical computing, computation and visualization in an integrated
environment. This document explains the basic concepts in MATLAB.
MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and
problem solving related to Linear Algebra.
MATLAB offers lots of additional Toolboxes for different areas such as Control Design, Image
Processing, Digital Signal Processing, etc.
Table of Contents
Preface..................................................................................................................................................... 2
Table of Contents ....................................................................................................................................iii
1
Introduction .................................................................................................................................... 1
1.1
2.1.2
Workspace ....................................................................................................................... 6
2.2.2
Current Directory............................................................................................................. 7
Variables .................................................................................................................................. 5
2.2.1
2.3
2.1.1
2.2
Help ......................................................................................................................................... 2
Scripts .................................................................................................................................... 12
4.2
Functions ............................................................................................................................... 13
Flow Control.................................................................................................................................. 15
5.1
5.2
5.3
5.4
Plotting.......................................................................................................................................... 17
iii
iv
Table of Contents
Vectors................................................................................................................................... 19
7.2
Matrices ................................................................................................................................. 20
7.2.1
Transpose ...................................................................................................................... 20
7.2.2
Diagonal ......................................................................................................................... 20
7.2.3
Triangular....................................................................................................................... 21
7.2.4
7.2.5
Matrix Addition.............................................................................................................. 22
7.2.6
Determinant .................................................................................................................. 22
7.2.7
7.3
Eigenvalues ............................................................................................................................ 24
7.4
7.5
LU factorization ..................................................................................................................... 26
7.6
7.7
Commands............................................................................................................................. 27
Toolboxes...................................................................................................................................... 28
General .................................................................................................................................. 31
9.2
Matrices ................................................................................................................................. 31
9.3
Linear Algebra........................................................................................................................ 31
1 Introduction
MATLAB is a tool for technical computing, computation and visualization in an integrated
environment, e.g.,
MATLAB is developed by The MathWorks. MATLAB is a short-term for MATrix LABoratory. MATLAB is
in use world-wide by researchers and universities.
For more information, see www.mathworks.com
Below we see the MATLAB Environment:
Command Window
Command History
1
Introduction
Workspace
Current Directory
The Command window is the main window. Use the Command Window to enter variables and to run
functions and M-files scripts (more about m-files later).
Watch the following Getting Started with MATLAB video:
http://www.mathworks.com/demos/matlab/getting-started-with-matlab-video-tutorial.html
1.1 Help
MATLAB has a comprehensive Help system.
I advise you to test all the examples in this text in MATLAB in order to get familiar with the program
and its syntax. All examples in the text are outlined in a frame like this:
Tutorial: Introduction to MATLAB
Introduction
>>
Command Window
The Command window is the main window. Use the Command Window to enter variables and to run
functions and M-files scripts (more about m-files later).
You type all your commands after the command Prompt >>, e.g., defining the following matrix
[
4
Or
>> A = [1,2;0,3]
>>a=4
>>b=3
>>a+b
2.1.2
Command History
Statements you enter in the Command Window are logged in the Command History. From the
Command History, you can view and search for previously run statements, as well as copy and
execute selected statements. You can also create an M-file from selected statements.
2.2 Variables
Tutorial: Introduction to MATLAB
Variables are defined with the assignment operator, =. MATLAB is dynamically typed, meaning that
variables can be assigned without declaring their type, and that their type can change. Values can
come from constants, from computation involving values of other variables, or from the output of a
function. For example:
>> x = 17
x =
17
>> x = 'hat'
x =
hat
>> x = [3*4, pi/2]
x =
12.0000
1.5708
>> y = 3*sin(x)
y =
-1.6097
3.0000
Unlike many other languages, where the semicolon is used to terminate commands, in MATLAB the
semicolon serves to suppress the output of the line that it concludes.
>> a=5
a =
5
>> a=6;
>>
As you see, when you type a semicolon (;) after the command, MATLAB will not respond.
2.2.1
Workspace
The Workspace window list all your variables used as long you have MATLAB opened.
This command lists all the command with the current values, dimensions, etc.
The command clear, will clear all the variables.
>>clear
2.2.2
Current Directory
Description
help
Help
help x
who, whos
clear
clear x
what
MATLAB is a "Matrix Laboratory", and as such it provides many convenient ways for creating vectors,
matrices, and multi-dimensional arrays. In the MATLAB, a vector refers to a one dimensional (1N or
N1) matrix, commonly referred to as an array in other programming languages. A matrix generally
refers to a 2-dimensional array, i.e. an mn array where m and n are greater than or equal to 1.
Arrays with more than two dimensions are referred to as multidimensional arrays.
MATLAB provides a simple way to define simple arrays using the syntax:
init:increment:terminator. For instance:
>> array = 1:2:9
array =
1 3 5 7 9
defines a variable named array (or assigns a new value to an existing variable with the name array)
which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value),
increments with each step from the previous value by 2 (the increment value), and stops once it
reaches (or to avoid exceeding) 9 (the terminator value).
The increment value can actually be left out of this syntax (along with one of the colons), to use a
default value of 1.
>> ari = 1:5
ari =
1 2 3 4 5
assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1
is used as the incrementer.
Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This
is atypical for programming languages, whose arrays more often start with zero.
Matrices can be defined by separating the elements of a row with blank space or comma and using a
semicolon to terminate each row. The list of elements should be surrounded by square brackets: [].
Parentheses: () are used to access elements and subarrays (they are also used to denote a function
argument list).
10
Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For
example, a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as:
>> A(2:4,3:4)
ans =
11 8
7 12
14 1
A square identity matrix of size n can be generated using the function eye, and matrices of any size
with zeros or ones can be generated with the functions zeros and ones, respectively.
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
>> zeros(2,3)
ans =
0 0 0
0 0 0
>> ones(2,3)
ans =
1 1 1
1 1 1
Most MATLAB functions can accept matrices and will apply themselves to each element. For
example, mod(2*J,n) will multiply every element in "J" by 2, and then reduce each element modulo
"n". MATLAB does include standard "for" and "while" loops, but using MATLAB's vectorized notation
often produces code that is easier to read and faster to execute. This code, excerpted from the
function magic.m, creates a magic square M for odd values of n (the built-in MATLAB function
meshgrid is used here to generate square matrices I and J containing 1:n).
[J,I] = meshgrid(1:n);
A = mod(I+J-(n+3)/2,n);
B = mod(I+2*J-2,n);
M = n*A + B + 1;
11
Description
eye(x), eye(x,y)
ones(x), ones(x,y)
zeros(x), zeros(x,y)
diag([x y z])
Diagonal matrix
size(A)
Dimension of matrix A
Inverse of matrix A
4.1 Scripts
Create a new m-file from the File New menu or the New button on the Toolbar.
12
13
4.2 Functions
You may create your own functions and save them as a m-file.
Example:
Create a function called linsolution which solve
Tutorial: Introduction to MATLAB
14
Below we see how the m-file for this function looks like:
You may define A and b in the Command window and the use the function on order to find x:
>> A=[1 2;3 4];
>> b=[5;6];
>> x = linsolution(A,b)
x =
-4.0000
4.5000
After the function declaration (function [x] = linsolution(A,b)) in the m.file, you may
write a description of the function. This is done with the Comment sign % before each line.
From the Command window you can then type help <function name> in order to read this
information:
>> help linsolution
Solves the problem Ax=b using x=inv(A)*b
Created By Hans-Petter Halvorsen
5 Flow Control
This chapter explains the basic concepts of flow control in MATLAB.
The topics are as follows:
If-else statement
Switch and case statement
For loop
While loop
15
16
Flow Control
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
6 Plotting
This chapter explains the basic concepts of creating plots in MATLAB.
Topics:
Function plot can be used to produce a graph from two vectors x and y. The code:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
Three-dimensional graphics can be produced using the functions surf, plot3 or mesh.
[X,Y] = meshgrid(-10:0.25:10,-10:0.25:10);
f = sinc(sqrt((X/pi).^2+(Y/pi).^2));
mesh(X,Y,f);
axis([-10 10 -10 10 -0.3 1])
xlabel('{\bfx}')
ylabel('{\bfy}')
zlabel('{\bfsinc} ({\bfR})')
hidden off
17
18
Plotting
7 Linear Algebra
Linear algebra is a branch of mathematics concerned with the study of matrices, vectors, vector
spaces (also called linear spaces), linear maps (also called linear transformations), and systems of
linear equations.
MATLAB are well suited for Linear Algebra.
7.1 Vectors
Given a vector x
Example:
[ ]
>> x=[1; 2; 3]
x =
1
2
3
>> x'
ans =
1
Orthogonality:
19
20
Linear Algebra
7.2 Matrices
Given a matrix A:
[
Example:
[
7.2.1
Transpose
Example:
[
>> A'
ans =
0
1
7.2.2
-2
-3
Diagonal
Example:
21
Linear Algebra
>> diag(A)
ans =
0
-3
Example:
>> eye(3)
ans =
1
0
0
7.2.3
0
1
0
0
0
1
Triangular
7.2.4
Matrix Multiplication
and
, then
where
22
Linear Algebra
Example:
>> A=[0 1;-2 -3]
A =
0
1
-2
-3
>> B=[1 0;3 -2]
B =
1
0
3
-2
>> A*B
ans =
3
-2
-11
6
Note!
7.2.5
Matrix Addition
and
, then
Example:
>> A=[0 1;-2 -3]
>> B=[1 0;3 -2]
>> A+B
ans =
1
1
1
-5
7.2.6
Given a matrix
Determinant
, then the Determinant is given:
23
Linear Algebra
| |
Then
| |
Example:
A =
0
1
-2
-3
>> det(A)
ans =
2
Notice that
and
Example:
>> det(A*B)
ans =
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
ans =
2
7.2.7
Inverse Matrices
is defined by:
24
Linear Algebra
if
is given by
[
Example:
A =
0
1
-2
-3
>> inv(A)
ans =
-1.5000
-0.5000
1.0000
0
Notice that:
7.3 Eigenvalues
Given
Example:
A =
0
1
-2
-3
>> eig(A)
ans =
-1
-2
25
Linear Algebra
may be written
][ ]
[ ]
where
[
]
[ ]
[ ]
In MATLAB you could also write x=A\b, which should give the same answer. This syntax can also be
used when the inverse of A dont exists.
Example:
26
Linear Algebra
7.5 LU factorization
LU factorization of
is given by
where
L is a lower triangular matrix
U is a upper triangular matrix
The MATLAB syntax is [L,U]=lu(A)
Example:
>> A=[1 2;3 4]
>> [L,U]=lu(A)
L =
0.3333
1.0000
1.0000
0
U =
3.0000
4.0000
0
0.6667
Or sometimes LU factorization of
is given by
where
D is a diagonal matrix
The MATLAB syntax is [L,U,P]=lu(A)
Example:
>> A=[1 2;3 4]
A =
1
2
3
4
>> [L,U,P]=lu(A)
L =
27
Linear Algebra
1.0000
0.3333
0
1.0000
3.0000
0
4.0000
0.6667
U =
P =
0
1
1
0
is given by
where
U is a orthogonal matrix
V is a orthogonal matrix
S is a diagonal singular matrix
Example:
>> A=[1 2;3 4];
>> [U,S,V] = svd(A)
U =
-0.4046
-0.9145
-0.9145
0.4046
S =
5.4650
0
0
0.3660
V =
-0.5760
0.8174
-0.8174
-0.5760
7.7 Commands
Command
[L,U]=lu(A)
Description
LU Factorization
[L,U,P]=lu(A)
[U,S,V] = svd(A)
8 Toolboxes
Toolboxes are specialized collections of M-files built for solving particular classes of problems, e.g.,
28
9 Whats Next?
There are lots of useful resources to dig into if you want to learn more about MATLAB.
Type demo in the Command window in MATLAB
>>demo
In the Getting Stated with Demos in the MATLA Help system you get access to tons of Demos in
form of M-files, Videos, etc.
30
Linear Algebra
MATLAB Graphics
Etc.
Quick Reference
9.1 General
Command
Description
help
Help
help x
who, whos
clear
clear x
what
9.2 Matrices
Command
Description
eye(x), eye(x,y)
ones(x), ones(x,y)
zeros(x), zeros(x,y)
diag([x y z])
Diagonal matrix
size(A)
Dimension of matrix A
Inverse of matrix A
Description
LU Factorization
31
Quick Reference
[L,U,P]=lu(A)
[U,S,V] = svd(A)