Sei sulla pagina 1di 18

INTRODUCTION TO MATLAB

Padmanabhan Seshaiyer
First Steps
You should start MATLAB by simply typing matlab if you are working on a Unix system or
just by double clicking the MATLAB icon if you are using a indows based system! "f all goes
well you will see a MATLAB prompt
>>
in#iting you to initiate a calculation! "n what follows$ any line beginning with %% indicates
typed input to MATLAB! You are expected to type what follows by not the %% prompt
itself! MATLAB supplies that automatically!

Arithmetic with MATLAB
MATLAB understands the basic arithmetic operations& '$ ($ )$ *! +owers are indicated with ,$
thus typing
>> 5*4 + 3^2
and pressing enter$ results in
ans =
29
The laws of precedence are built in but if in doubt$ you should put parentheses appropriately! -or
example$
>> 7+3*(2/(8-2))
ans =
8
The sort of elementary functions familiar on hand calculators are also a#ailable! -or example$
>> sqt(3^2+4*4)
ans =
5
>> e!p(l"#(3$2))
ans =
3$2
Padmanabhan Seshaiyer
Using Variables
You can assign numerical #alues to variables for use in subse.uent calculations! -or example the
volume of a sphere can be calculated #ia the following se.uence&
>> adius = 3%
>> &"lume=(4/3)*pi*adius^3
&"lume =
''3$(973
/ote that the first line did not seem to produce a result in screen! hen MATLAB encounters an
instruction followed by a semi(colon 0 it suppresses any #isual confirmation! "t really does obey
the instruction and records the #alue of the #ariable in the memory! This is useful if you want to
a#oid cluttering up the screen with intermediate results! 1ach #ariable must somehow be
assigned before you make use of it in further calculations! -or example if you ha#e followed the
abo#e example with$
>> !=4*pi*adius*)
you should get the result$
??? Undefined function or variable 'h'
This is self(explanatory! "f you now type
>> )=3%
>> !=4*pi*adius*)
you should ha#e more success! "ncidentally$ a .uick way of repeating a pre#ious MATLAB
instruction is to press the 2up(arrow3 key until you reco#er the command you need! You may
also use the sideways arrows to modify any of the pre#ious commands!
At any point typing the command$
>> *)"
tells about all the #ariables that are in the workspace of the current MATLAB session!
Vectrs
A #ector can be input in se#eral ways! -or example$
>> u=+' 3 5,;
>> &=+'-3-5,%
>> *='.2.5%
All three commands abo#e yield the same #ector! 4ne can perform #ector operations such as$
>> /=u+&-*%
Padmanabhan Seshaiyer
/ote that the #ectors described so far are row #ectors! To get a corresponding column #ector$ we
in#oke the transpose of a #ector! -or example$
>> u0
ans =
'
3
5
The difference between the #ectors u and u3 can be understood by typing the commands
>> si/e(u)
>> si/e(u0)
which yields the row si5e followed by the column si5e for each #ector! 4ne can now multiply
#ectors appropriately to either yield an innerproduct
>> /=u*u0
or a matrix$
>> /=u0*u
Multiplication of #ectors only happens if the inner matrix dimensions agree! -or example$
>> u*u
would yield$
??? Error using ==> *
Inner matrix dimensions must agree.
6uppose we want a set of #alues / gi#en by / = u
2
then we want
>> / = u$*u%
where the ! is inserted before the ) symbol which forces an element(by(element operation!
6imilarly u!*# and u!,7 can be understood to be the corresponding element(by(element
operations!
"#ample& 6uppose we want to find the distance between two points A and B whose position
#ectors are gi#en by a 8 9:$ ;< and b 8 9=$ =< respecti#ely! The following se.uence of commands
can be executed in MATLAB to obtain the desired result&
>> a=+' 2,%
>> b=+5 5,%
>> d = b 1 a%
>> dd = d*d0%
>> dist2ab = sqt(dd)
Padmanabhan Seshaiyer
Script Files
/ow suppose we want to modify the position #ectors and find the distance between the new
coordinates$ it will not be worthwhile to type all the commands again! "nstead one can create a
script file$ which will contain all the necessary information! To create a new script file$ one can
open their fa#orite text editor and type the following commands$

3 dist2ab$m
3 4al5ulates distan5e bet*een any t*" p"siti"n &e5t"s a and b
d=b-a%
dd=d*d0%
dist2ab=sqt(dd)

6a#e these contents in a file named dist_ab.m and note that the script file has a 2!m3 extension
which denotes that it is a MATLAB file! /ow one can pick #alues for the #ectors a and b by
simply typing say$
>> a=+' 2 3,%
>> b=+5 5 3,%
Then find the distance by simply typing
>> dist2ab
dist2ab =
5
This program can be called repeatedly to find the distance between any two position #ectors that
are entered by the user!

F$nctin Files
"t was tedious to ha#e to assign the two #ectors each time before using the abo#e script file! 4ne
can combine the assignment of input #alues with the actual instruction$ which in#okes the script
file by using a function m-file! /ot only that$ but also one can at the same time assign the answer
to an output #ariable!
To create a new function file$ one can open their fa#orite text editor and type the following
commands$

Padmanabhan Seshaiyer
3 dist6n$m
3 4al5ulates t)e distan5e bet*een t*" &e5t"s a and b
3 7nput. a- b (p"siti"n &e5t"s)
3 8utput. dist2ab is t)e distan5e bet*een a and b
6un5ti"n dist2ab = dist6n(a - b)
d= b 1 a%
dd = d*d0%
dist2ab = sqt(dd)%

6a#e these contents in a file named distfn.m and we should now be able to run$
>> dist2ab=dist6n(+' 2 3,- + 5 5 3,)
"
>> a=+' 2 3,%
>> b=+5 5 3,%
>> dist2ab=dist6n(a - b)%
To sa#e a certain part of the work in the MATLAB session$ one can type$
>> diay *"9'
>> :$
>> :$
>> diay "66
All the work between the diary commands will be sa#ed into a file called work1!

%mewr&& >reate a function file to deduce the maximum length of the side of a triangle AB>
whose position #ectors are gi#en by a$ b$ c!
4ne of the most useful commands in MATLAB is the )elp command! -or e!g!$ you can type$
>> )elp sin
>> )elp sqt
and so on! Also note that$
>> )elp dist6n
would return the comments that were entered at the beginning of the program written in the
session!

Padmanabhan Seshaiyer
Matrices
To 'e(ine a matri# you start with its name! 6.uare brackets are used to begin and end each
matrix! You can separate elements with a space or a comma$ and end each row with a semi(colon
like this&
%% A 8 ?:$ ;$ (@0 A$ =$ ;0 (;$ :$ BC
or this&
%% A 8 ?: ; (@0 A = ;0 (; : BC
"n either case you ha#e defined the same 7 by 7 matrix named A and you can use it at any time in
a calculation or to define another matrix by using its name 9A<!
1xamples&
%% B 8 ?; (D A C
B is a : by 7 row matrix
%% > 8 ?;0 (D0 A0 C
> is a 7 by : column matrix
%%E 8 ?=$ F$(;0 7$(D$ =C
E is a ; by 7 matrix
You can e'it indi#idual elements of a matrix as follows&
%% A9:$:< 8 (= changes the element in row: column: of matrix A to (=
%% E9;$7< 8 B changes the element in row; column7 of matrix E to B
To perform peratins on matrices you use the symbols 9 )* +* , < from the number keypad or
abo#e the numbers across the top of the keyboard!
Padmanabhan Seshaiyer
1xamples&
%% A ' A adds the matrix A to itself!
%% B ) > multiplies B and >
%% >)B ( A A is subtracted from the product of > and B
The symbol - 9abo#e the number @< is used to raise a matrix to an exponent as follows&
%% A,7 cubes the matrix A 9you might also use A)A)A for the same calculation<
%% >)E an error message is displayed Matlab will gi#e an error message when the
calculation cannot be done because of a dimension mismatch!
To sol#e the system of e.uations for 9x$ y$ 5< using Gaussian 1limination&
a x ' b y ' c 5 8 u
e x ' f y ' g 5 8 #
p x ' . y ' r 5 8 w
we perform the following steps in matlab!
%% A 8 ?a b c0 e f g0 p . rC0
%% b 8 ?u0 #0 wC0
%% M 8 ?A bC0
%% H 8 rref9M<0
%% I 8 H9D$ :&7<0
Padmanabhan Seshaiyer
Mre help($l MATLAB cmman's.
/$it or e#it either of these closes the program and ends your matlab session!
sa0e filename this command will sa#e all #ariables 9and 4/LY the #ariables ( /4T the whole
session< that you ha#e defined in the current session! This is helpful when you enter large
matrices that you want to work with at a later date!
la' filename this command loads the #ariables that you sa#ed in a pre#ious session!
lpr this is the command used to print your diary file! 1I"T TJ1 MATLAB +H4GHAM!
At the osf: prompt$ type& lpr +1st223 filename 9note& st;;B is the printer in 6T " room ;;B! At
other locations you will use another printer name after the (1 <
wh displays #ariables you ha#e defined in your current session
wh4 matlab answers the .uestion!9again and again<
clear clears all #ariables from your current session! 4nly use this command if you want to
lose e#erything!
5 this is used for comments! Matlab ignores any line that begins with K
Matlab has many built in matrix functions and operators! " ha#e listed some here that you may
find useful&
%% si6e9A< gi#es the dimension of the matrix A
%% in09A< calculates the in#erse of the matrix A $ if it exists!
%% 'et9A< calculates the determinant of the matrix A
%% rre(9A< calculates the row reduced echelon form of the matrix A
%% A7 forms the transpose of the matrix A!
%% e4e 9;$;< this is the ; by ; identity
%% 6ers 97$7< builds the 5ero matrix of any dimension
%% nes 97$;< fills a matrix of any si5e with ones!
%% rats9A< displays elements of the matrix A as fractions
%% (rmat lng displays all numbers with := digits instead of the usual D digits
Padmanabhan Seshaiyer
Sme $se($l b$ilt+in ($nctins.
Elementary trigonometric functions and their inverses
sin$ cos$ tan$ sec$ csc$ cot$ asin$ acos$ atan$ asec$ acsc$ acot
Elementary hyperbolic functions and their inverses
sinh$ cosh$ tanh$ sech$ csch$ coth$ asinh$ acosh$ atanh$ asech$ acsch$ acoth
Basic logarithmic and exponentiation functions
log$ log;$ log:B$ exp$ s.rt$ pow
Basic Statistical functions
max$ mean$ min$ median$ std$ #ar$ sum
Basic complex number functions
imag$ real$ i$ j$ abs$ angle$ cart;pol
Basic data analysis functions
fft$ ifft$ interpn$ spline$ diff$ del;$ gradient
Basic logical functions
and$ or$ xor$ not$ any$ all$ isempty$ is)
Basic polynomial operations
poly$ roots$ residue$ polyfit$ poly#al$con#
Function functions that allows users to manipulate mathematical expressions
fe#al$ fminbnd$ f5ero$ .uad$ ode;7$ odeD=$ #ectori5e$ inline$ fplot$ explot
Basic matrix functions
5eros$ ones$ det$ trace$ norm$ eig
Try the following&
>> 6=;2+5"s(!);%
>> 6=inline(6)%
>> 6pl"t(6-+(-2*pi,)
>> !=6/e"(inline(;5"s(!);-;!;)-')
Padmanabhan Seshaiyer
1ltting Basics
6uppose we wish to plot the graph y=!
2
in the inter#al ?(:$ :C$ then just type$
>> ! = -'.($'.'
>> y=!$*!
>> pl"t(!-y)
/ote that the axes are automatically chosen to suit the range of #ariables used! 4ne can add more
features to the plot using the following commands&
>> title(<=ap) "6 y=!^20)
>> !label(<!0)
>> ylabel(<y0)
6uppose now we want to plot the graphs y
'
=!
2
and y
;
8;x on the same figure$ we need$
>> y'=!$*!%
>> y2=2*!%
>> pl"t(!-y')
>> )"ld "n
>> pl"t(!-y2-0"0)
/ote that the )"ld "n command tells MATLAB to retain the most recent graph so that a new
graph can be plotted! /ote that axes are adjusted and the second cur#e is plotted with a red circle!
More options on the choice for the color and symbol can be found by typing$
>> )elp pl"t
6uppose we want to plot the graphs y
'
=!
2
and y
;
8;x on the same figure but partitioned into two
subplots then we say$
>> subpl"t(2-'-')
>> pl"t(!-y')
>> subpl"t(2-'-2)
>> pl"t(!-y2)
4ne must now be able to employ the #arious plotting commands in #arious combinations to get
the desired figure!
Padmanabhan Seshaiyer
Cn'itinal Statements.
for Lps.
This allows a group of commands to be repeated a fixed$ predetermined number of times! The
general form of a 6" loop is&
6" ! = aay
4"mmands :
>nd
-or example$
>> 6" n='.'(
!(n)=sin(n*pi/'()%
end
yields the #ector x gi#en by$
>> !
! =
4"lumns ' t)"u#) 7
($3(9( ($5878 ($8(9( ($95'' '$(((( ($95'' ($8(9(
4"lumns 8 t)"u#) '(
($5878 ($3(9( ($((((
Let us now use the for loop to generate the first := -ibonacci numbers :$:$;$7$=$F$L
>> 6=+' ',%
>> 6" 9='.'5
6(9+2) = 6(9+') + 6(9)%
end
>> 6
Padmanabhan Seshaiyer
while Lps
This e#aluates a group of commands an infinite number of times unlike the 6" loop that
e#aluates a group of commands a fixed number of times! The general form for while loop is
*)ile e!pessi"n
4"mmands :
end
-or example to generate all the -ibonacci numbers less than :BBB$ we can do the following&
>> 6=+' ',%
>> 9='%
>> *)ile 6(9) ? '(((
6(9+') = 6(9+') + 6(9)%
9 = 9 +'%
end
>> 6
Padmanabhan Seshaiyer
i(+else+en' Cnstr$ct
There are times when a se.uence of commands must be conditionally e#aluated based on a
relational test! This is done by the if(else(end construct whose general form is$
i6 e!pessi"n
4"mmands :
end
-or example if we want to gi#e ;BK discount for larger purchases of oranges$ we say$
>> "an#es='(% 3 numbe "6 "an#es
>> 5"st = "an#es*25 3 4"st "6 "an#es
5"st =
25(
>> i6 "an#es > 5
5"st = ('-2(/'(()*5"st%
end
>> 5"st
5"st =
2((
"f there are more conditions to be e#aluated then one uses the more general if(else(end construct
gi#en by$
i6 e!pessi"n
4"mmands e&aluated i6 @ue
else
4"mmands e&aluated i6 Aalse
end
Padmanabhan Seshaiyer
switch+case Cnstr$ct
This is used when se.uences of commands must be conditionally e#aluated based on repeated
use of an e.uality test with one common argument! "n general the form is$
s*it5) e!pessi"n
5ase test2e!pessi"n'
4"mmands2' :
5ase test2e!pessi"n2
4"mmands22 :
:$$
"t)e*ise
4"mmands2n :$
end
Let us now consider the problem of con#erting entry in gi#en units to centimeters!
K centimeter!m
K This program con#erts a gi#en measument into the e.ui#alent in cms
K "t illustrates the use of 6"T>J(>A61 control flow
6un5ti"n y=5entimete(B-units)
s*it5) units 3 5"n&et B t" 5ms
5ase C;in5);-;in;D
y = B*2$54%
5ase C;6eet;-;6t;D
y = B*2$54*'2%
5ase C;mete;-;m;D
y = B*'((%
5ase C;5entimete;-;5m;D
y = B%
"t)e*ise
disp(+;En9n"*n units. ; units,)
y = nan% 33 stands 6" n"t a numbe
end

Padmanabhan Seshaiyer
Character Strings.
"n MATLAB$ these are arrays of A6>"" #alues that are displayed as their character string
representation! -or example&
>> t = <Fell"0
t =
Fell"
>> si/e(t)
ans =
' 5
A character string is simply text surrounded by single .uotes! 1ach character in a string is one
element in the array! To see the underlying A6>"" representation of a character string$ you can
type$
>> d"uble(t)
ans =
'(4 '(' '(8 '(8 '''
The function char pro#ides the re#erse transformation&
>> 5)a(t)
ans =
)ell"
6ince strings are numerical arrays with special attributes$ they can be manipulated just like
#ectors or matrices! -or example$
>> u=t(2.4)
u =
ell
>> u=t(5.-'.')
u =
"lle)
>> u=t(2.4)0
u =
e
l
l
4ne can also concatenate strings directly! -or instance$
Padmanabhan Seshaiyer
>> u=0Gy name is 0%
>> &=0G$ GB@HBI0%
>> *=+u &,
* =
Gy name is G$ GB@HBI
The function disp allows you to display a string without printing its #ariable name! -or
example&
>> disp(*)
Gy name is G$ GB@HBI
"n many situations$ it is desirable to embed a numerical result within a string! The following
string con#ersion performs this task!
>> adius='(% &"lume=(4/3)*pi*adius^3%
>> t=+<B sp)ee "6 adius < num2st(adius) < )as &"lume: "6 <
num2st(&"lume) 0$0,%
>> disp(t)
"t may sometimes be re.uired to find a certain part of a longer string! -or example$
>>a=0@e!as @e5) Eni&esity0%
>>6indst(a-0 <) 33 Ainds spa5es
ans =
@ J ''
>>6indst(a-0@e5)0) 33 Ainds t)e stin# @e5)
ans
7
>>6indst(a-;@e;) 33 Ainds t)e stin# statin# *it) @e
ans =
' 7
>>6indst(a-0te5)0) 33 @)is 5"mmand is 5ase-sensiti&e
ans =
+ ,
"f it is desired to replace all the case on Tech to T1>J then one can do this by using$
>>step(a-0@e5)0-0@>4F0)
ans =
@e!as @>4F Eni&esity
Padmanabhan Seshaiyer
Relatinal Operatrs.
These include the operators ? ?= > >= == K=
These operators can be used to compare two arrays of the same si5e$ or to compare an array to a
scalar! -or example&
>> B='.5- I=5-B
B =
' 2 3 4 5
I =
4 3 2 ' (
>> #=B>3
# =
( ( ( ' '
finds elements of A that are greater than 7! Meros appear in the result where this condition is not
satisfied and ones appear where it is!
>> 6" n=2.J
i6 em(n-2)K=(
n
end
end
n =
3
n =
=
Padmanabhan Seshaiyer
Lgical Operatrs.
The three main logical operators are& A/E$ 4H$ /4T which are represented by the symbols N$ O$
P respecti#ely in MATLAB! 4ften one can combine these operators with relational expressions!
-or example&
>> #=(B>2) L (B?5)
# =
( ( ' ' (
returns ones where A is greater than ; A/E less than =!
>> 6" n=2.J
i6 (em(n-2)K=() L (em(n-3)K=()
n
end
end
n =
5
-inally$ the abo#e capabilities make it easy to generate arrays representing discontinuous
functions$ which are #ery useful in understanding signals etc! The basic idea is to multiply those
#alues in an array that you wish to keep with ones$ and multiply all other #alues with 5eros! -or
example$
>> ! = -2.($'.2% 3 4eates Mata
>> y = "nes(si/e(!))%
>> y = (!>-')L(!?')%
>> pl"t(!-y)
This should plot a function which resembles part of a s.uare wa#e that is discontinuous at !=-'
and !='!
Padmanabhan Seshaiyer

Potrebbero piacerti anche