MATLAB
MATLAB
MATLAB is aprogram for doing numerical computation.
MATLAB is a program for doing numerical computation.
It was originally designed for solving linear algebra type
It was originally designed for solving linear algebra type
problems using matrices. It
problems using matrices. It’
’s name is derived from
s name is derived from
MATrix LABoratory.
MATrix LABoratory.
MATLAB has since been expanded and now has built-in
MATLAB has since been expanded and now has built-in
functions for solving problems requiring data analysis,
functions for solving problems requiring data analysis,
signal processing, optimization, and several other types
signal processing, optimization, and several other types
of scientific computations. It also contains functions for
of scientific computations. It also contains functions for
2-D and 3-D graphics and animation.
2-D and 3-D graphics and animation.
3.
MATLAB
MATLAB
When you firstopen MATLAB, notice:
When you first open MATLAB, notice:
1.
1. The
The command window
command window is where you'll give
is where you'll give
MATLAB its input and view its output.
MATLAB its input and view its output.
2.
2. The
The workspace
workspace shows you all of your current
shows you all of your current
working variables and other objects.
working variables and other objects.
3.
3. The
The history
history shows you all commands you used
shows you all commands you used
in CW.
in CW.
4.
4. The
The Editor
Editor for MATLAB scripts (M-files) . To
for MATLAB scripts (M-files) . To
save & run the m-file type 'F5'. To open the
save & run the m-file type 'F5'. To open the
editor with a new or old m-file use the command
editor with a new or old m-file use the command
open
open file_name
file_name
4.
MATLAB help
MATLAB help
Forhelp, command description etc use F1 or following
For help, command description etc use F1 or following
commands:
commands:
help
help command_name
command_name
helpwin
helpwin command_name
command_name
doc
doc command_name
command_name
helpdesk
helpdesk command_name
command_name
demo
demo command_name
command_name
lookfor
lookfor keyword
keyword (search unknown command)
(search unknown command)
http://www.mathworks.com/support/
http://www.mathworks.com/support/
For example when running
For example when running “
“help sin
help sin”
” one get
one get
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also ASIN, SIND.
Overloaded functions
Reference page in Help browser doc sin
5.
Some Useful commands
SomeUseful commands
what
what List all m-files in current directory
List all m-files in current directory
dir/ls
dir/ls List all files in current directory
List all files in current directory
type test
type test Display test.m in command window
Display test.m in command window
delete test
delete test Delete test.m
Delete test.m
cd/chdir
cd/chdir Change directory
Change directory
pwd
pwd Show current directory
Show current directory
which test
which test Display directory path to
Display directory path to ‘
‘closest
closest’
’ test.m
test.m
who
who List known variables
List known variables
whos
whos List known variables plus their size
List known variables plus their size
clear
clear Clear variables from workspace
Clear variables from workspace
clc
clc Clear the command window
Clear the command window
6.
MATLAB & Matrices
MATLAB& Matrices
MATLAB treats all variables as matrices. For our
MATLAB treats all variables as matrices. For our
purposes a matrix can be thought of as an array, in fact,
purposes a matrix can be thought of as an array, in fact,
that is how it is stored.
that is how it is stored.
Vectors are special forms of matrices and contain only
Vectors are special forms of matrices and contain only
one row OR one column.
one row OR one column.
Scalars are matrices with only one row AND one column
Scalars are matrices with only one row AND one column
7.
Variable Names
Variable Names
Variablenames
Variable names ARE
ARE case sensitive
case sensitive
Variable names can contain up to 63 characters (as of MATLAB 6.5
Variable names can contain up to 63 characters (as of MATLAB 6.5
and newer). One can use
and newer). One can use namelengthmax
namelengthmax command to
command to
verify it.
verify it.
Variable names must start with a letter followed by letters, digits,
Variable names must start with a letter followed by letters, digits,
and underscores.
and underscores.
MATLAB variables are defined by assignment. There is no need to
MATLAB variables are defined by assignment. There is no need to
declare in advance the variables that we want to use or their type.
declare in advance the variables that we want to use or their type.
Example
Example
x=1;
x=1; % Define the scalar variable x
% Define the scalar variable x
y=[1 2 3]
y=[1 2 3] % row vector
% row vector
z=[1;2;3]
z=[1;2;3] % column vector
% column vector
A=[1 2 3;4 5 6;7 8 9]
A=[1 2 3;4 5 6;7 8 9] % 3x3 matrix
% 3x3 matrix
whos
whos % List of the variables defined
% List of the variables defined
Note: terminate statement with semicolon (;) to suppress output.
Note: terminate statement with semicolon (;) to suppress output.
8.
Special Variables
Special Variables
ans
ansDefault variable name for results
Default variable name for results
pi
pi Value of
Value of π
π
eps
eps Smallest incremental number
Smallest incremental number
inf
inf Infinity
Infinity
NaN
NaN Not a number
Not a number e.g. 0/0
e.g. 0/0
i,j,1i,1j
i,j,1i,1j imaginary unit
imaginary unit i,
i, i.e.
i.e. square root of -1
square root of -1
realmin
realmin The smallest usable positive realnumber
The smallest usable positive realnumber
realmax
realmax The largest usable positive real number
The largest usable positive real number
SpecialVars.m
SpecialVars.m
9.
Other symbols
Other symbols
>>
>>prompt
prompt
. . .
. . . continue statement on next line
continue statement on next line
,
, separate statements and data
separate statements and data
%
% start comment which ends at end of line
start comment which ends at end of line
;
; (1)
(1) suppress output
suppress output
(2)
(2) used as a row separator in a matrix
used as a row separator in a matrix
:
: specify range
specify range
10.
Relational Operators
Relational Operators
MATLABsupports six relational operators.
MATLAB supports six relational operators.
Less Than
Less Than <
<
Less Than or Equal
Less Than or Equal <=
<=
Greater Than
Greater Than >
>
Greater Than or Equal
Greater Than or Equal >=
>=
Equal To
Equal To ==
==
Not Equal To
Not Equal To ~=
~=
11.
Math & AssignmentOperators
Math & Assignment Operators
Power
Power ^
^ or
or .^
.^ a^b
a^b or
or a.^b
a.^b
Multiplication
Multiplication *
* or
or .*
.* a*b
a*b or
or a.*b
a.*b
Division
Division /
/ or
or ./
./ a/b
a/b or
or a./b
a./b
or
or
or
or .
. ba
ba or
or b.a
b.a
NOTE:
NOTE: 56/8 = 856
56/8 = 856
-
- (unary)
(unary) +
+ (unary)
(unary)
Addition
Addition +
+ a + b
a + b
Subtraction
Subtraction -
- a - b
a - b
Assignment
Assignment =
= a = b
a = b (assign
(assign b
b to
to a
a)
)
Operators.m
Operators.m
12.
MATLAB Logical Operators
MATLABLogical Operators
MATLAB supports five logical operators.
MATLAB supports five logical operators.
not/~
not/~ element wise/scalar logical NOT
element wise/scalar logical NOT
and/&
and/&element wise logical AND
element wise logical AND
or
or / |
/ | element wise logical OR
element wise logical OR
&&
&& logical
logical (short-circuit) AND
(short-circuit) AND
||
|| logical
logical (short-circuit) AND
(short-circuit) AND
13.
Logical Functions
Logical Functions
MATLABalso supports some logical functions.
MATLAB also supports some logical functions.
xor
xor (a, b) exclusive or
(a, b) exclusive or
any
any(x) returns 1 if any element of x is nonzero
(x) returns 1 if any element of x is nonzero
all
all(x)
(x) returns 1 if all elements of x are
returns 1 if all elements of x are
nonzero
nonzero
isnan
isnan(x) returns 1 at each NaN in x
(x) returns 1 at each NaN in x
isinf
isinf(x) returns 1 at each infinity in x
(x) returns 1 at each infinity in x
finite
finite(x) returns 1 at each finite value in x
(x) returns 1 at each finite value in x
find
find(x)
(x) find indices and values of non zero elements
find indices and values of non zero elements
14.
Some Matrix functions
SomeMatrix functions
zeros
zeros(rows, cols) – create zero matrix
(rows, cols) – create zero matrix
rand
rand(rows, cols) – generate random matrix
(rows, cols) – generate random matrix
ones
ones(rows, cols) – matrix with 1 in all entries
(rows, cols) – matrix with 1 in all entries
eye
eye (rows, cols) – identity matrix
(rows, cols) – identity matrix
sub2ind
sub2ind,
, ind2sub
ind2sub indices manipulation
indices manipulation
15.
Extracting a Sub-Matrix
Extractinga Sub-Matrix
A portion of a matrix can be extracted and stored in a
A portion of a matrix can be extracted and stored in a
smaller matrix by specifying the names of both matrices
smaller matrix by specifying the names of both matrices
and the rows and columns to extract. The syntax is:
and the rows and columns to extract. The syntax is:
sub_matrix = matrix ( r1 : rn , c1 : cn ) ;
sub_matrix = matrix ( r1 : rn , c1 : cn ) ;
sub_matrix = matrix ( r1 : rn , : ) ;
sub_matrix = matrix ( r1 : rn , : ) ;
sub_matrix = matrix ( : , c1 : cn ) ;
sub_matrix = matrix ( : , c1 : cn ) ;
sub_matrix = matrix ( r1 : dr : rn , c1 : dc : cn ) ;
sub_matrix = matrix ( r1 : dr : rn , c1 : dc : cn ) ;
where
where r1
r1 and
and rn
rn specify the beginning and ending rows
specify the beginning and ending rows
and
and c1
c1 and
and cn
cn specify the beginning and ending
specify the beginning and ending
columns to be extracted to make the new matrix.
columns to be extracted to make the new matrix.
The terms
The terms dr
dr and
and dc
dc define spacing different than one.
define spacing different than one.
matrix.m
matrix.m
16.
“
“Continuous
Continuous”
” functions
functions
Numerically, wecannot represent a general continuous function
Numerically, we cannot represent a general continuous function
(x,f(x)) because it requires handling infinite data (for each point in
(x,f(x)) because it requires handling infinite data (for each point in
the range, we need to keep f(x)). Instead, we represent a function
the range, we need to keep f(x)). Instead, we represent a function
by its values at a finite number of data points (x_i,f(x_i)), where the
by its values at a finite number of data points (x_i,f(x_i)), where the
series of points {x_i} is typically referred to as the sampling points or
series of points {x_i} is typically referred to as the sampling points or
the grid points. Accordingly, the "continuous" functions in Matlab
the grid points. Accordingly, the "continuous" functions in Matlab
accepts a vector of point {x_i} and return a vector of values {f(x_i)}.
accepts a vector of point {x_i} and return a vector of values {f(x_i)}.
Some functions
Some functions
sqrt
sqrt
log
log
cos/acos/sin/asin etc
cos/acos/sin/asin etc
exp - exponential
exp - exponential
abs
abs
sign
sign
norm
norm
sum
sum
prod - product
prod - product
17.
Plotting
Plotting
MATLAB will plotone vector vs. another. The first one will be treated
MATLAB will plot one vector vs. another. The first one will be treated
as the abscissa (or x) vector and the second as the ordinate (or y)
as the abscissa (or x) vector and the second as the ordinate (or y)
vector. The vectors have to be the same length.
vector. The vectors have to be the same length.
MATLAB will also plot a vector vs. its own index. The index will be
MATLAB will also plot a vector vs. its own index. The index will be
treated as the abscissa vector. Given a vector
treated as the abscissa vector. Given a vector “
“time
time”
” and a vector
and a vector
“
“dist
dist”
” we could say:
we could say:
>> plot (time, dist)
>> plot (time, dist) % plotting versus time
% plotting versus time
>> plot (time + i*dist)
>> plot (time + i*dist) % plotting versus time
% plotting versus time
>> plot (dist)
>> plot (dist) % plotting versus index
% plotting versus index
Sometime we want to see it with different colorline stile
Sometime we want to see it with different colorline stile
>> plot (time, dist, line_characteristics)
>> plot (time, dist, line_characteristics)
And sometime we want to plot few functions in graphs
And sometime we want to plot few functions in graphs
>> plot(…), hold, plot(…)
>> plot(…), hold, plot(…)
>> plot(t,d1,l_c1, t,d2, l_c2)
>> plot(t,d1,l_c1, t,d2, l_c2)
To split page to several axes check use
To split page to several axes check use
>> subplot (rows, cols, place)
>> subplot (rows, cols, place)
19.
Plotting
Plotting
There are commandsin MATLAB to "annotate" a plot to put on axis
There are commands in MATLAB to "annotate" a plot to put on axis
labels, titles, and legends. For example:
labels, titles, and legends. For example:
To put a label on the axes we would use:
To put a label on the axes we would use:
>> xlabel ('X-axis label')
>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')
>> ylabel ('Y-axis label')
To put a title on the plot, we would use:
To put a title on the plot, we would use:
>> title ('Title of my plot')
>> title ('Title of my plot')
To distinct between function in the graph use:
To distinct between function in the graph use:
>> legend(legend_1, legend_2)
>> legend(legend_1, legend_2)
plotting.m
plotting.m
20.
Flow control (condition)
Flowcontrol (condition)
An if - elseif - else structure. (Note that elseif is
An if - elseif - else structure. (Note that elseif is one
one word)
word)
if
if expression1
expression1
statements1
statements1
elseif
elseif expression2
expression2
statements2
statements2
else
else
statements3
statements3
end
end
An switch-case structure
An switch-case structure
switch
switch switch_expr
switch_expr
case
case case_expr
case_expr
statement, ..., statement
statement, ..., statement
case
case {case_expr1, case_expr2, case_expr3, ...}
{case_expr1, case_expr2, case_expr3, ...}
statement, ..., statement
statement, ..., statement
otherwise
otherwise
statement, ..., statement
statement, ..., statement
end
end
21.
Flow control (loops)
Flowcontrol (loops)
A for loop in MATLAB
A for loop in MATLAB
for
for ind = 1:100
ind = 1:100
b(ind)=sin(ind/10)
b(ind)=sin(ind/10)
end
end
Alternative (Most of the loops can be avoided!!!):
Alternative (Most of the loops can be avoided!!!):
x=0.1:0.1:10;
x=0.1:0.1:10;
b=sin(x);
b=sin(x);
A while loop in
A while loop in
while
while x <= 10
x <= 10
% execute these commands
% execute these commands
end
end
22.
M-Files
M-Files
An
An M-file
M-file mightbe used as a
might be used as a script
script, i.e. file consist set
, i.e. file consist set
of statements
of statements
In additional, one use M-files to write
In additional, one use M-files to write function
function, in this
, in this
case the file starts with function definition like:
case the file starts with function definition like:
function y = f(x)
function y = f(x)
function [u,v] = f(x,y,z)
function [u,v] = f(x,y,z)
File name
File name and the
and the name of function
name of function in the file are
in the file are
usually
usually identical
identical, however while they are different,
, however while they are different,
MATLAB use file name to call function.
MATLAB use file name to call function.
If you add additional function in same M-file, it
If you add additional function in same M-file, it
considered sub-function and might be called from inside
considered sub-function and might be called from inside
the M-file only. Only the first function might be called
the M-file only. Only the first function might be called
from outside.
from outside.
23.
Saving Results
Saving Results
Wecan save all our results for future reference
We can save all our results for future reference.
.
The command
The command
diary
diary ‘
‘FileName'
FileName'
saves all output to command window into the FileName.txt file until
saves all output to command window into the FileName.txt file until
this option is turned off by the command
this option is turned off by the command
diary off
diary off
The following commands save & load the entire workspace
The following commands save & load the entire workspace
into the file 'MyMatFile.mat'
into the file 'MyMatFile.mat'
save 'MyMatFile'
save 'MyMatFile'
load 'MyMatFile'
load 'MyMatFile'
save 'x.mat' x
save 'x.mat' x %
% save a specific variable
save a specific variable
saving in ASCII format:
saving in ASCII format:
x = (-1:0.4:1)' ;
x = (-1:0.4:1)' ; y = sin(x*pi)
y = sin(x*pi)
var = [x y]
var = [x y] % double-column
% double-column
save 'my_sin.dat' -ASCII -double var
save 'my_sin.dat' -ASCII -double var %
%Save in 16-digit ASCII format
Save in 16-digit ASCII format
24.
MATLAB also havehumor
MATLAB also have humor
why
why % try this command
% try this command