MATLAB Unit 1 Study Material
MATLAB Unit 1 Study Material
UNIT 1 INTRODUCTION
Menus & Tool bars, Variables – Matrices and Vectors- initializing vectors- data types-
Functions –user defined functions-passing arguments-writing data to a file-reading data from a
file- using functions with vectors and matrices- cell arrays & structures -Strings -2D strings-
String comparing- Concatenation – Input and Output statements - Script files
MATLAB® is a very powerful software package that has many built-in tools for solving
problems and for graphical illustrations. The simplest method for using the MATLAB product is
interactively; an expression is entered by the user and MATLAB immediately responds with a
result. It is also possible to write programs in MATLAB, which are essentially groups of
commands that are executed sequentially. This chapter will focus on the basics, including many
operators and built-in functions that can be used in interactive expressions. Means of storing
values, including vectors and matrices, will also be introduced.
lookfor searches through the help for a specific string (be aware that this can take a long
time)
To get out of MATLAB, either type quit at the prompt, or chooses File, then Exit MATLAB
from the menu. In addition to the Command Window, there are several other windows that can
be opened and may be opened by default. What is described here is the default layout for these
windows, although there are other possible configurations. Directly above the Command
Window, there is a pull-down menu for the Current Directory. The folder that is set as the
Current Directory is where files will be saved. By default, this is the Work Directory, but that
can be changed.
To the left of the Command Window, there are two tabs for Current Directory Window and
Workspace Window. If the Current Directory tab is chosen, the files stored in that directory are
displayed. The Command History Window shows commands that have been entered, not just in
the current session (in the current Command Window), but previously as well. This default
configuration can be altered by clicking Desktop, or using the icons at the top-right corner of
each window: either an ―x,‖ which will close that particular window; or a curled arrow, which in
its initial state pointing to the upper right lets you undock that window. Once undocked, clicking
the curled arrow pointing to the lower right will dock the window again.
The variable is always on the left, followed by the assignment operator, = (unlike in
mathematics, the single equal sign does not mean equality), followed by an expression. The
expression is evaluated and then that value is stored in the variable. For example, this is the way
it would appear in the Command Window:
>> mynum = 6
mynum
=6
>>
Here, the user (the person working in MATLAB) typed mynum = 6 at the prompt, and
MATLAB stored the integer 6 in the variable called mynum, and then displayed the result
followed by the prompt again. Since the equal sign is the assignment operator, and does not
mean equality, the statement should be read as
―mynum gets the value of 6‖ (not ―mynum equals 6‖). Note that the variable name must always be
ontheleft, and the expression on the right. An error will occur if these are reversed.
>> 6 = mynum
??? 6 = mynum
|
Error: The expression to the left of the equals sign is not a valid target for an
assignment. Putting a semicolon at the end of a statement suppresses the output.
For example,
>> res = 9 – 2;
>>
This would assign the result of the expression on the right side, the value 7, to the variable res; it
just doesn‘t show that result. Instead, another prompt appears immediately. However, at this
point in the Workspace Window the variables mynum and res can be seen.
Note: In the remainder of the text, the prompt that appears after the result will not be shown. The
spaces in a statement or expression do not affect the result, but make it easier to read. The
following statement that has no spaces would accomplish exactly the same thing as the previous
statement:
>> res = 9–2;
MATLAB uses a default variable named ans if an expression is typed at the prompt and it is not
assigned to a variable. For example, the result of the expression 6 3 is stored in the variable ans:
>> 6 + 3
ans
=9
This default variable is reused any time just an expression is typed at the prompt. A short-cut for
retyping commands is to press the up-arrow, which will go back to the previously typed
command(s). For example, if you decided to assign the result of the expression 6 3 to the variable
res instead of using the default ans, you could press the up-arrow and then the left-arrow to
modify the command rather than retyping the whole statement:
>> res = 6 + 3
res
=9
This is very useful, especially if a long expression is entered with an error, and you want to go
back to correct it. To change a variable, another assignment statement can be used that assigns
the value of a different expression to it. Consider, for example, the following sequence of
statements:
>> mynum = 3
mynum
=3
>> mynum = 4 + 2
mynum =
6
>> mynum = mynum + 1
mynum
=7
In the first assignment statement, the value 3 is assigned to the variable mynum. In the next
assignment statement, mynum is changed to have the value of the expression 4 2, or 6. In the
third assignment statement, mynum is changed again, to the result of the expression mynum 1.
Since at that time mynum had the value 6, the value of the expression was 6 1, or 7. At that point,
if the expression mynum 3 is entered, the default variable ans is used since the result of this
expression is not assigned to a variable.
Thus, the value of ans becomes 10 but mynum is unchanged (it is still 7). Note that just typing
the name of a variable will display its value.
>> mynum + 3
ans =
10
>>
mynum
On-line Help:
Variables temporamy
used t t o r e v2lues
-Variabes ave
paricular
at a
value fs stored
Ostng Variabes,a
memony locatiom symbol or
addressed with
a
respecively
a =
>Y= 3
WoKspace pane
-
7C = a+y
C 4
d = a"y
1 The Symbol raísesthe Pswer oanother number)
e= Y/2 -
2* 4
e = - 2.5000
new
The commands for c, d'2nd e'w?ll cve ate
Variables
TheSe Variables are added to The WoKSPace
ENaluate EXpYessiOng.
-We can abo agk MATLAB tw
MATLABs
at
command, loo
TUping the follohim
respomse end WorksP-re
(Ctd/e
ans =
2
Created a neh Var able
-he C an S e e That MA TLAB has
called ans
tDre the esult
This Vanzble Cans) is wsed to
OUur xpressiOn Values u callkcd as
numencal
VzOu
NOECASumbol
Khich takes
2 VaN>ble.
VariaHe Tames
have aflexibJity io detide the
names
Tn We
MATLAB,
or Vriables.
We giv/e to
are framed Dased on
Vaile names in MATLAR
Some Guidelines, They are
rne
D MATLAB is case Sensihve (ie Upper Caselapltel)
LOerCaselSmall leters).
aifererh Variables,
names.
nd MYVari2-are Vald Variable
E MYVari2, MY-Var12,
names
Var+able
12Myvar and -MyVari2 are fn Vaid
Same
shouled not be the
The Variable n a m e s diven by Us
TommOn MATLABVariables
MOSt Ommon type MATLAB Vanabes re:
C)doble and i ) char
double:
that holds eal,
o Tt's a common MATLAB Variable
MATLAB
to a number,
hhene Variable name îs 2cighea
created in MATLABe
automatically
doule ís
CTyre Vaiable)
statement:
For Exarnple, h e follooing
Var- 1O 5
Ceted
For £Xample, the follosing statement creates a
Variable ot tyRe Cha .The n a m e CVariable Char
S comment
Var = Commemt
be 2
comment nSil|
After the statemet is Eecuted,
X 26 character 2rray
Note
Vaiables n MATLAB may be Createc any ime, by
them.
t2ssigning Values to
tells the
The tyPe o dala assigned to,Varíable,
Created.
Variable that 1S
type ot
e =
EARTH (char tupe variable).
numerical Value a
COnstnts: A symbol having a ixed Constnt
(Parheular) V2lue
-Constant takes a spe cific
2 pra ram.
fxecttion
aluringthe
-
Value Rehumed
Name
Most recent anshNer
error
tolerance for floanng
eps
Foint o P e r a t i o n s .
CDefaulEValue 2.2204X10).
unit (-1)
Tmagn a y
a
Tnfinity (£3, The result
divisiom by O)
array fs
- An
is list Mwnbers or £xpreSsion S
Am aray a
coLumns.
rons" and "VerHcal
2TYarged în hovizontal
hame.
- T t is Knawn by a Single
the humber
an array fs Specifed
by
The Size o in The arra4
Couumns
a n d The numberaL
roNS
Ro RoN i
Ron 2 -
RON 3 -
Ro
ROW4|
9p
(one dimensional
Coli CO 22 Co3 Col4 Cods CBG
Array Size
3X) 2r2y
conteining 3 element,
(column Vector),
he Contenb the arry may be e d or modfied
t any time
and
term division,
term by-
tesm-by- tevm Exponeniation.
more dlmensions
one or
arY2Yp con have.
LAB
arrays bith
as many dmension
-
MATLAB allo S US to c r e a t e
h e matríx
COmmands 2re
eome
Retume the
number o£lemens A
lengthA)
.Size[A)> ReTums he Size a marx A.
a VectoY
are c2lled as Vectors
1 - Dimencional arrays
X=
12
is a c o l u m m Vectov
Here Y
Y= C2: 1!5] LOith t h r e e £lements
-UsingSemicoons ne
Y Column Vector,
Specify a
Vector to a OUm
-ote We cannot add (or) eubtract a
Vector
coumn. in a matrix
T t s td be moted that, £very ro Or
s called as a Vector
Built-in MATLAB Funchons
built -
in funcioms for:
-MATLAB has hundreds O
Cay Technical computabon
Grphics and
(C) Animathon.
tools for
MATLABS buitt-în-funchions piont de £xcellent
Tumerical and Scienti fic comput2h srms,
FoY Example,
is a functhion that calculates the Square
SqrtCx)
root O a number. Here, t h e name i s SyrE and
aYgument 1S X
> expl5)
exPCX) Exponential (e) ans -
148 4132
> abs(-24)
abs(x) Absolute Value ans E
Functhon Description
ConvertS a mar*x of numbers intd a
chartx chaYacter string-
ans
O+1.414214
Creating and rinting Simple Plots
-One of the met ponierful teature o} MATLAB is the
device-Jndependent plotting capability.
- Hence, it ís Very £asy to Plot any data a t n y
time
- TO Plot a data, he use the Plottunction.
Print Prints a
hardeoPy O the Plot
Equaton
cose, y= Sing O e < 21T
Soluhon
Meth
data.
(1 Eist generate the
HereWe comSíder
- and y-co oYdinates of, say,
Plot
Print
Print on the default
Printer.
MATLAB desktoP.
2) Lme Styles
Make the Same plot as in Bxercise 1, but rather than displayins
the a p h as acurve, sho the unconnected data poits.
-TO díSplay the data points ith Sm2ll carcles, use plot(x,Y, 'o),
N o n Combine the tho Plots ith The commandi
plot(x, ¥, X, Y, o)
Ans TyPe the follonin roiam in the tditor pindo MATLAB
3) Space Cuve
civeular helix
Use the command plot3X,Y,z) to Plot the
- S t n t , ylt) = cOst, zlE) = E, O3E s20.
in the ínterval.
5) Log-scale plots
Create a Vector X= O;Lo:1O0O, lot
i Vs using three
0 9 - S c a l e plot c o m m 2 n d s .
X=O:1o: 1oOO
Y= X."3:
Semilogx (X,Y)
Semilogy(x,Y)
1oglog (xY)
EXercíses(2-D pots)
6) OVerlay plots:
Plot y-Cosz and z= 1- 2 for Osz<tt on The
Plot
i n t : YouL can use plot(x, Y,x, z , ( - - ) or You can Plt the
De:
a user-created file th a sequence
A SeriPt file
it.
MATLAB COmmands tn
(OY)
A ceript file 1S an external Ale that contains a SeAuenc
CMATLAB Satements.
its n2me.
Execut a t he2
by typing its
name
* SCYriptfile e r e u t e d
Commnd prompt.
should appear
AneN edit (editor) +Sîndoh
on UN1X WoTKstations;
unes
Plot ca,4)D: % Pot the circle
axls ('eua'); 7Set equal scaleon
aNes
ttle (circle of un't radíus')
Put a +itle.
(b Weite and eaVe the Ale:
Blank
he PrOgram that- is aready typed in the
M-file ís Saved under the name: circle.m
o n tS
()Select Save AS.... trom the file menu.
in he COmmand Ninda).
help circle
wnit circle.
Circle -A Script file to dr2N a
7 circle.
(Sol pocedue
-Fndlude the foloiin g Command
in the seri pt file
before the first Executable Jine Ctheta.
axiseaual);
ttle
7 Set £qual seale On sxes
51 Line
I t s the first commented line before any xecutable
Statement tn a
ScriptHle.
>lookfor
the H1 ine,
The ookfor Command is used to seareh
Exampes
ExamPle i
ConSider the System of
EoLations;
Proramfexamplei.m)
t 2y+ 3z 1 A 2 2:3 3 4 2 3
NOte:
TO Execute the funchion circlefn In tree different Ways
try the folloing:
R 5
> X,Y = cYclefn(R):
cívclefn(R'2/X+5 "stn(r)))
Exerclses
) Convert temperature
-WYite a function that outputs a cnversfon table for cels+us
and Fahvenheit'temperatures. h e input of the. funthion shaud
bC To umbers: Tt and TeSpecifing the loner and upper range
Othe tale n celeius.
The output shaubl be a two columm matix : the fivst
Couumn shoning the temperaturein celsius frcm Ti to Te in
2nd
The încemênts of Lc, The Second cALmn Shan the
Cowe
stonding temperatuves în fahvenheit Sc:es
PIOcedue;
SteP-1 Create 2 cdum Vector c from T to Te Jith the
Command
Tnittal to Tinal
Fet32
Command;
Sfrep -3: Make the fnalmatx ith he
temp CF|
Here, he Ouuput Van4le s temP
YOgram:-
fuwnction temptable = ctof (tinTtial, tfihal):
yCTO F unchon to i Vert tenmperatie fromCbo
Cal1 Syntax:
temptable=ctof[tinibal tfnalJ
-
C =F-32
Here C= celsius TemeYature
Scole.
F: FahYenhief temperature
Scale.
For cel9ies scale,
C gCE-32)
Temperature
tn. celsius, CF-32)
FoY Fahvenhtet scale
Re-arnging,
oC=F-32"
c P-32.
TemPeratur
in paenhiet
+ 32
2) calcudate factrials:
Write a funchon factorial to compte the factorial m! for any 9en
intefer n. The input shold be the nunber n n he aulpt
sShold be m!.
int32, int 32
int 64, uint64
d losical:
This type data stores oolean Values 1 r O.
They caan be operated by Boolean operators ike
AND, OR, XOR etc.
-(e) ehar
Thistype data tores alphabetic characters and
strings.
SMgs means, jrOup Charaders NTitten in a
Seyuermce.
-f cell 2nd struchure
Cellnd structure. rays Can store sifferent tyfes q
d a t a in the Same Nray.
OperatoS
Operator s a smbol that tells the compler to jertom
Specific mathenatical or logical manfptllatians.
Smbol Role
Equal to
Not Gqual to
Greater than
Sreaterthan or Eual to
Les than
CAiD Loficalorerators
These operrs pefom lofical qaraticns like AND, OR NOT éte
Thele OperaoYS HoIK n h e Sme- Way as telehona operatos,
They pro dute Vectors or malnces he s2me Size.
mbol Role
loscal Compleotb
XOr exclusiVe OR
Precedene OeratiON
Relatioal Operators
-
aL OP 2|
FHeYe aL and 22 are arithmetic txpvessions, Variables or
Strings, and cop is one h e operators.
6Lofical opexators
-Lofical operators ave operstoYs ith one ov tNO lofical
OperandS,
The enersl fpim binany lofic orerabion S
Pogrom confrol-flon
rogram control statementS are the Commands that
lter the. Sequential flaN a comruter Program.
2
CD if- e d structuve 1f-ele-end shuchvc -elseif-else-end
Symtax Syryax utax
Ff logicalexpression expression logical.exPreSsion
statements tatements
Statemerts
ese
end.
Statements
elseif
Statements
emd eSe
Statemetts
2md
Its he slmplestfiYm Its the more comple t the mot ComPlex
FoTm fo
VExample Programfor If- eleeif- else stakments.
16je21 :
Case Value 2
block2 computatiom
otheroíse
end
For ex>mple
proram for findin all poers 2 elaw loOco-
Vi
ume1
Syrt2x
while expression
code bloc'k
end
if 1 = 3;
break;
end
tPontf (if =
zam, ii);|
end
disp(C'nd af loop!;
The Oultrut the Profim ater beinf £xectlted is as shoun,
test-reak
i 2
End of Loop!
Tts Northy to note that, the break statement
was Executed
On the terabn hen 1 was 3.
-
Withat Executing the
tprntf statement, the Contro Was
tafeel to the Srst Execttabe
staternent.
) Continue cmmand/statement
-The cothnue statement termu'nates the cuvent
Pass
through the loopP.
Tt retums control to the top the loop.
-
Cotinue
end
fprintfC°ff= d\n', if);
nd
disP(C'endof loop!')
h e n ths
pogY am is
Axauted, the autput IS
test-Contînue-
ii 2
115
End of Loop