Matlab Fundamentals
Prepared and conducted by
Dr.Archana Singh| Index
= About Matlab
= The basics
= Advanced operations
= Examples
= Advanced Graphics and Plotting
&is Matlab (MATrix LABoratory)
MATLABG is a high-performance language for technical computin
= It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation.
= MatLab is an interactive system whose basic data element is an array that
does not require dimensioning.
«= MatLab features a family of add-on application-specific solutions called
toolboxes which are collections of MatLab functions (M-files) that extend the
MatLab environment to solve particular classes of problems.
Typical uses for Matlab Construction
Math and computation = Core functionality: compiled C-routines
Aigorithm development = Most functionality given as m-files grouped into toolboxes
Data acquistion a m¢iles contain source code, can be copied and altered
Modeling, simulation, and a miles are platform independent (PC, Unix/Linux, MAC)
prototyping «= Simulation of dynamical systems is performed in Simulink.
Data analysis, exploration, Gente. Syst)
and visualization
Scientific and engineering graphics
Appligation development, including
q buildingHow to start and exit Matlab
Ona Microsoft Windows platform, to start MATLAB, double-click the MATLAB
shortcut \.con on your Windows desktop.
After starting MATLAB, the MATLAB desktop opens.
Note the >> is the matlab command prompt.
To end your MATLAB session, select Exit MATLAB from the File menu in the
desktop, or type quit in the Command Window.
Note that nothing is saved when you exit, you will not be prompted to save
MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools (GUI) for
managing files, variables, and applications associated with MATLAB.[= oo ae oe oe eee oe
COO a rel ome
[Fete Cornette ene
for issuing commands and seeing results
Cemetery restos)
list of files in the user directory currently
eed
owe ah preeniyentecomGhetcspaeperrmnrtap Se pe ben wmWhat Matlab operates on?
= MATLAB works with scalars, vectors and matrices.
A scalar is just a number, a 1x1 matrix,
A vectors a list of numbers, effectively a matrix, given as either a row or a column.
In this sense, everything that MATLAB operates on is a matrix.
The best way to get started with MATLAB is to learn how to handle matrices.
Command Window
‘Command Window is used to enter variables and run functions and files.
Navigation within MATLAB is done using regular UNIX commands
acd (change directory)
a pwd (show the path)
tals (list contents of directory)
a whos (list of the variable stored in the memory)| The Basics
Variables and Arrays
= Array: A collection of data values organized into
rows and columns, and known by a single name.
Row 1—>
Row 2—+
|
ar(3,2) > =
1 ot !
(\ Col 1 Col 2 Col 3 Col 4 ColArrays
= The fundamental unit of data in MATLAB
= Scalars are also treated as arrays by
MATLAB (1 row and 1 column).
= Rowand column indices of an array start
from 1.
= Arrays can be classified as vectors and
matrices.
&= Vector: Array with one dimension
= Matrix: Array with more than one dimension
= Size of an array is specified by the number of
rows and the number of columns, with the
number of rows mentioned first (For example: n
x m array).
Total number of elements in an array is the
product of the number of rows and the number
(i columns.Initializing Variables in Assignment Statements
= Arrays are constructed using brackets and
semicolons. All of the elements of an array are listed
in row order.
The values in each row are listed from left to right
and they are separated by blank spaces or
commas.
The rows are separated by semicolons or new lines.
The number of elements in every row of an array
must be the same._———————_—@€£€
Special Values
pi: z value up to 15 significant digits
i, j: sqrt(-1)
Inf: infinity (such as division by 0)
NaN: Not-a-Number (division of zero by zero)
clock: current date and time in the form of a 6-
element row vector containing the year, month, day,
hour, minute, and second
date: current date as a string such as 16-Feb-2004
eps: epsilon is the smallest difference between two
numbers
ans: stores the result of an expression>.
Changing the data format
>> value = 12.345678901234567;
format short
format long
format short e
format long e
format short g
format long g
format rat
— 12.3457
~ 12.34567890123457
— 1.2346e+001
— 1.234567890123457e+001
— 12.346
— 12.3456789012346
— 1000/81Dealing with Matrices
= Once you have a matrix, you can refer to
specific elements in it.
«Matlab indexes matrices by row and column. c(3,1) is
the element in the third row, 1st column, which is 4.
C(2:3,1:2) gives you the elements in rows 2-3, and
columns 1-2, so you get
27
43
as a result. c(1:3,2) gives you the elements in rows 1-3,
and the second column, that is, the entire second
column. You can shortcut this to: c(:,2)
» You can get a whole row of a matrix with c(1,:)
&Help and other tools
Typing ‘help atthe matlab prompt gives you a lst of al the possible directories
matlab can find commands in (which also tells you its "search path’, or a list of
the directories it is looking in for commands.)
Typing “help directoryname" gives you a list of the commands in that directory
and a short description of them
Typing “help commandname” gives you help on a specific command.
Typing "lookfor keyword" gives you a list of commands that use that keyword. ie,
"lookfor integral” lists commands that deal with integrals. It's pretty slow, choose
the word wisely. You can use control-c to stop searching when you think you've
found what you need.
Typing "doc" starts up a web browser with the Matlab. This includes the entire
reference manual for matlab, a whole lot of other information on using matlab,
and a pointer to the Matlab Primer, a good introduction to using Matlab.
&Some Useful Tools:
Warning: Never use any key word as the variable name
= If you accidentally reassign a function name
to a variable (ie, you try saying sum = 3 and
then you get errors when you try to use the
sum function because it doesn't know it's a
function anymore), you can restore it to its
normal state using "clear functionname". You
can also use clear to get rid of all variable
values with “clear all".
&who
2 will tell you all the variables you have currently defined.
whos
a will tell you the variables, their sizes, and some other info.
pi
a is a function of that returns the value of pi.
eps
a is a function that returns Matlab's smallest floating point
number.
a= format long and format short
a switch between the long and short display format of
numbers. Either way matlab uses the same number of
digits for its calculations, but normally (format short) it will
only display the first four digits after the decimal point.
= Typing type Function
a name for any function in Matlab's search path lets you see
how that function is written.
Check difference between commands help and type
a| Plotting
= The basic syntax to get a plot in matlab is
plot(x1,y1)
2 (The x values always come before the y values, x1 and y1
represent variables that your data is stored in.) If you type a
second plot command later, it will clear your first plot. If you
type “hold on" it will hold the current plot so you can add
plots on top of one another (until you reset it by typing "hold
off".)
a You can plot multiple values with plot(x1,y1,x2,y2)
and you can specify the color and linetype of a
plot as something like plot(x1,y1,'w*’) to get white
*'s for each data point= To split your plot into a bunch of smaller
plots, you can use the subplot command to
split it up into rows and columns.
= subplot(r,c,n)
a will split the plot window into r rows and c columns of plots
and set the current plot to plot number n of those rows and
columns.
= You can add titles, labels, and legends to plots.
title(‘This is a Title’)
» xlabel('My X axis’)
ylabel(My Y axis’)
legend(First Thing Plotted’,'Second Thing Plotted’)old on
suplot(212)
latin
tive(Pot of random 100 values’)
label’Samrpling stan’)
ylabe’Random Numbers’)
subplo(332)
plot(x*k’)
tive(Pot of random 100 values)
‘label Sampling instars’)
Yiabel(Random Numbers’)
subploy(332)
plotter)
tive(Pot of random 100 values’)
label Sampling instars’)
ylabeRandom Numbers’)Printing, Saving, and Loading
Basic printing
= >>print -Pprintername
You can also save to a Postscript or Encapsulated
Postscript file:
= >>print -dps filename.ps
= >>prind -deps filename.eps
You can also save your plot as an m-file (matlab
script) which should contain all the commands you
need to recreate your plot later.
= =>>print -dmfile filename.m= You can save and load files as either text
data or matlab's own data format. If you have
a text file consisting of a bunch of columns of
data separated by spaces or tabs, you can
load it into matlab with
= load filename.dat
= The above command will give you a matrix
called filename. Then you can reassign
columns of that matrix, i.e.
= coll = filename(:,1);
&= When you save data using the command
a Save filename.mat
= matlab will save all of your variables and their
values in its own format, so that when you
load it using
a load filename.mat
= you will have all of your variables already
defined and names.
&Writing Functions and Scripts
= All matlab functions and scripts are plain text
files that contain matlab commands. Matlab
will treat any file that ends in .m as either a
function or a script.
= Scripts
« Ascriptis just a list of commands to be run in some
order. Placing these commands in a file that ends in .m
allows you to "run the script by typing its name at the
command line. You type the name of the script without
the .m at the end.
&Accessing matrix elements
= Elements of a matrix are accessed by specifying the row
and column
>> A=[1 2 3,45 6; 789);
>> x=A(1,3)
a Returns the element in the first row and third column
>> y=A(2,:)
a Returns the entire second row [4 5 6]
a “:" means “take all the entries in the column”
>> B=A(1:2,1:3)
a Returns a submatrix of A consisting of rows 1 and 2
and all three columns [1 2 3; 4 5 6]
&Arithmetic matrix operation
= The basic arithmetic operations on matrices
are:
+ addition
- subtraction
* multiplication
/ division
* power
oooad
o
’ conjugate transpose
a 0element-by-element operations
= MATLAB provides element-by-element
operations by prepending a ‘.’ before the
operator
.* multiplication
/ division
“ power
.’ transpose (unconjugated)
aRelational operations
= MATLAB defines the following relational
operations:
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to| Logical operations
= MATLAB defines the following logical
operations:
a &and
a | or
a ~ not
a| Math functions
= The following functions operate element-wise
when applied to a matrix:
sin cos tan
asin acos atan
sinh cosh tanh
exp log(natural log) log10
abs sqrt sign| M-files
MATLAB is an interpretive language
M-files are text files containing MATLAB scripts
Scripts are sequences of commands typed by an
editor
The instructions are executed by typing the file
name in the command window at the MATLAB
prompt
All the variables used in the m-file are placed in
MATLAB’s workspace that contains all the variables
defined in the MATLAB session
a| M-files Debug
In Matlab you can debug your m-file, like in other
programming languages
To do it, you need to open your matlab file from the window
command.
Afterwards, you can operate exactly like for other
languages and you can use usual command as:
step in
step out
break point
etc. etc
&Matlab Statements and Variables
= MATLAB is an expression language. It
interprets and evaluates expressions typed in
the command window at the keyboard.
= You are allowed to assign a name to an
expression.
= Statements are usually in the form of
variable = expression,
e.g. A= magic(4)Interactive Calculations
Matlab is interactive, no need to declare variables
>> 24+3*4/2
>> a=5e-3; b=l; atb
Most elementary functions and constants are
already defined
>> cos(pi)
>> abs(1ti)
>> sin(pi)
Last call gives answer 1.2246e-016 !?
a|
Floating point numbers in Matlab
= IEEE Standard for double precision numbers
: 2 12 13 64
= Round-off: eps =252
= Underflow: real min = 2-022
= Overflow: real max = (2-eps) -22023| Variable and Memory Management
«Matlab uses double precision (approx. 16
significant digits)
m>> format long
=>> format compact
#All variables are shown with
=>> who
m=>> whos
=Variables can be stored on file
m>> save filename
=>> clear
m>> load filename
&| The Help System
= Search for appropriate function
= >> lookfor keyword
= Rapid help with syntax and function definition
a >> help function
= An advanced hyperlinked help system is
launched by
a >> helpdesk
co manuals as PDF filesVectors and Matrices
= Vectors (arrays) are defined as
a>>ve=[1, 2, 4, 5]
a>>we=[l; 2; 4; 5]
= Matrices (2D arrays) defined similarly
m>> A =[1,2,3;4,-5,6;5,-6,7]
&Matrix Operators
&
All common operators are overloaded
>> v +2
Common operators are available
>> B =A’
>> A*B
>> A+B
Note:
Matlab is case-sensitive
A and a are two different variables
Transponate conjugates complex entries;
avoided by
>> B=A.'| Indexing Matrices
«Indexing using parentheses
=>> A(2, 3)
=lndex submatrices using vectors
of row and column indices
=>> A([2 3],[1 2])
»Ordering of indices is important!
=>> B=A([3 2],[2 1])
>> B=[A(3,2),A(3,1);A( 2,2); A(2,1)]
aIndexing Matrices
=lndex complete row or column using
the colon operator
=>> A(1,:)
=General notation for colon operator
=a>> vel:5
& wel: 2:5
=Can also add limit index range
a>> A(1:2,:)
=e>> A([1 2],:)Matrix Functions
Many elementary matrices predefined
>> help el mat;
>> | =eye( 3)
Elementary functions are often overloaded
>> help el mat
>> sin(A)
Specialized matrix functions and operators
>> As=sqrtm( A)
>> As*2
>> ALFA
Note: in general,”Dot Operator” ”.” is
elementwise operation
&| Numerical Linear Algebra
= Basic numerical linear algebra
mw >> z=[1;2;3]; x=inv(A)*z
m>> xsA\z
= Many standard functions predefined
= >> det(A)
= >> rank(A)
= >> eig(A)
= The number of input/output arguments can often
be varied
m>> [V, D] =ei g( A)
a| Syntax - symbols and punctuation
= Try these examples
Input
Output
Comments
243
75
34°212
1234/5786
295
Arithmetic works as expected.
Note that the result is given the name “ans” each time.
a= sqri(2)
a= 1.4142
You can choose your own names for things.
ab=a, pi, 2+3i
ans = 2.0000 +
3.00001
You can use commas to put more
than one command on a line. Pi, i,
and j are contants.
c=sin(pi)
eps
c= 1.2246e-016
ans = 2.2204e-016
“eps” is the current limit of
precision. Anything smaller than
eps is probably zero. Note that
Matlab understands (and expects
you to understand!) scientific
notation.
d=
[123456789
23456789
23456789
f=123456789
"d","e", and "f' are all vectors.
They are equal. Note the use of
the ":" operator - it counts (by
ones) from one number to the
next.
g=0246810
ans = 3
ans = 234567
123456789
More uses of the colon. Note that
you can use it to get slices of a
vector (or matrix, or cube, etc), or
get the whole thing.(nothing)
ans =1
2
Asemi-colon ";" will prevent the output
from being displayed. A single quote "'
“ computes the transpose of a matrix,
or in this case, switches between row
and column vectors.
Operations on vectors. * is matrix
multiplication, and so the dimensions
line up correctly.
is entry-by-entry multiplication.
Entering a matrix.
Accessing matrix elements.
Note use of ":" to access an entire row.Output
Comments
ans = 30 36 42
66 81 96
102 126 150
ans= 149
16 25 36
49 64 81
The first multiplies the matrix by itself.
The second squares each entry in the
matrix.Matrix Operations Synopsis
+,-,*, and / are defined in an intuitive
manner for matrices
“** (transposition) turns a row vector into a
column vector
“*" (dot-star) will multiply entry-by-entry
“” will do matrix multiplication. More
precisely,
&
CH. )=YALK)* BK, j)
4| Transposing Matrices
= The special character “ ‘ “ (prime or apostrophe)
denotes the transposition of the matrix. The
statements
=» A=[123;45 6; 780]; B=A;
Result in
a A= B=| Mattrix-Vector Product
= Matrix-Vector Product is a special case of
general matrix-matrix product.
= Letus
A=[123;456; 780]; x=[-102];
=» b=A\%*x results in the output
b=
5
8
7
a| Using Powers with Matrices
= A‘p raises A to p-th power and is defined if Ais a
square matrix and p is a scalar.
= If pis an integer greater than 1, the power is
computed by repeated multiplication.
= For other values of p, the calculation involves
eigenvalues (D) and eigenvectors (V):
if [V.D] = eig(A), then
then Ap = V*D.%p/V
= X*P, where both X and P a matrices, is an error.
&| Matrix built-in operations
= For more, type help matfun
Input Output Comments
k= [16 2 3; k=16 2 3
5 11 10; 5 11 10 Define a matrix.
9 7 6) 976
rank(k) 3 The rank.
det(k) The determinant.
a| Matrix built-in operations, Cont.
Input
Output
Comments
inv(k)
ans =
Inverse of the
matrix
[vec, val] =
eig(k)
Eigenvectors
and eigenvalues
of the matrix.
The columns of
"vec" are the
eigenvectors,
and the diagonal
entries of "val"
are the
eigenvaules
&| Matrix built-in constructions
= For more, type help func_name
Input
Output
Comments
rand(2)
rand(2,3)
ans =
ans
-9501,
+2311
-8913
-7621.
6068
4860
-4565
0185
Generates a matrix with
entries randomly distributed
between 0 and 1
zeros(2)
ones(2)
e
Generates a 2x2 matrix with
all zero (or all ones) entries.
eye(2)
Identity matrix I.
hilb(3)
3x3 Hilbert matrix.| Deleting rows and columns
= You can delete rows and columns from a matrix
using just a pair of square brackets.
= Startwih X=[123;456;780]
Then, to delete the second column of X, use
X(,2) =[];
Thus, X= [1 3
4 6
7 0]
= If you delete a single element from a matrix, the
result isn’t a matrix anymore.
= So, expressions like
) X(1,2) =[], result in an error.Concatenating Matrices, Cont.
a=[1 2;3 4]
output
ans =1
ans =
[a, zeros(2); zeros(2), a']
&M - files
= You can create your own matrices using M-files,
which are text files containing MATLAB code.
Use the MATLAB Editor or another text editor to
create a file containing the same statements you
would type at the MATLAB command line. Save the
file under a name that ends in .m.
For example, create a file containing these two lines.
A=[16.03.0 2.0 13.0; 5.0 10.0 11.0 8.0; ...
9.0 6.0 7.0 12.0; 4.0 15.0 14.0 1.0];
Store the file under the name magik.m. Then the
statement magik reads the file and creates variable,
A, containing our example matrix.
a| Solving System of Linear Equations
= One of the main uses of matrices is in representing
systems of linear equations.
= Ifais a matrix containing the coefficients of a
system of linear equations, x is a column vector
containing the “unknowns,” and b is the column
vector of “right-hand sides," the constant terms, then
the matrix equation
ax=b
represents the system of equations
aSolving equations, Cont.
= MATLAB uses the division terminology
familiar in the scalar case to describe the
solution of a general system of simultaneous
equations.
= The two division symbols, slash, /, and
backslash, \, are used for the two situations
where the unknown matrix appears on the left
or right of the coefficient matrix.
&| Solving equations, Cont.
= X= A\B denotes the solution to the matrix equation
AX =B.
X = B/A denotes the solution to the matrix equation
XA=B.
The dimension compatibility conditions for X = A\B
require the two matrices A and B to have the same
number of rows.
The solution X then has the same number of
columns as B and its row dimension is equal to the
column dimension of A.
For X = B/A, the roles of rows and columns are
interchanged.Solving equations, Cont.
In practice, linear equations of the form AX = B
occur more frequently than those of the form XA =
B. Consequently, backslash is used far more
frequently than slash.
The coefficient matrix A need not be square. If A is
m-by-n, there are three cases.
m=n, Square system. Seek an exact solution.
m > n, Overdetermined system. Find a least squares
solution.
m > plot(x,y)
a produces a graph of y versus x, where x and y are
two vectors
x=linspace(0,2*pi,100);
plot(x,sin(x));
&Line styles and colors
= Itis possible to specify color, line styles, and markers
when you plot your data using the plot command
plot(x,y,'color_style_marker')
color_style_marker is a string containing from one to four
characters constructed from a color, a line style, and a
marker type:
a Color strings: ‘c’, 'm’, 'y’, 'r’, ‘g’, ‘b’, ‘w’', and ‘k’. These
correspond to cyan, magenta, yellow, red, green, blue,
white, and black
a Linestyle strings are ‘-' for solid, '--' for dashed, ':' for
dotted, '-.' for dash-dot, and ‘none’ for no line
\ The marker types are '+', ‘o’, *' and ‘x’Axis lables and titles
= xlabel(‘string')
a labels the x-axis of the current axes
= ylabel(‘string')
a labels the y-axis of the current axes
= Title(‘string’)
a add a title to a graph at the MATLAB command
( prompt or from an M-file