0% found this document useful (0 votes)
95 views

MATLAB Unit 1 Study Material

The document provides an introduction to MATLAB, including: 1) MATLAB is a mathematical software package used for numerical calculations, graphical illustrations, and programming. It has many built-in functions and toolboxes for tasks like signal processing. 2) The main components of the MATLAB interface are the Command Window, where commands can be entered interactively, and various toolbars and windows for files, variables, and command history. 3) Variables are used to store and manipulate values in MATLAB. They are assigned values using assignment statements of the form "variablename = expression". This allows storing numbers, strings, matrices, and other objects in variables to be used in calculations and programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

MATLAB Unit 1 Study Material

The document provides an introduction to MATLAB, including: 1) MATLAB is a mathematical software package used for numerical calculations, graphical illustrations, and programming. It has many built-in functions and toolboxes for tasks like signal processing. 2) The main components of the MATLAB interface are the Command Window, where commands can be entered interactively, and various toolbars and windows for files, variables, and command history. 3) Variables are used to store and manipulate values in MATLAB. They are assigned values using assignment statements of the form "variablename = expression". This allows storing numbers, strings, matrices, and other objects in variables to be used in calculations and programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

SEC1618-PROGRAMMING IN MATLAB

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.

MATrix LABoratory (MATLAB)


o Basically deals with interactive matrix calculations
o Special purpose computer program optimized to perform Engineering and Scientific
calculations
 Has built in integrated development environment
o Supports different platform ( windows 9x/NT/ 2000, Unix,etc.,)
o Has extensive library and built in functions for various field.
o MATLAB complier is an interpreter
o Includes tools that allow Graphical User Interface (GUI)
 Visit : https://in.mathworks.com

GETTING INTO MAT LAB


MATLAB is a mathematical and graphical software package; it has numerical, graphical, and
programming capabilities. It has built-in functions to do many operations, and there are
toolboxes that can be added to augment these functions (e.g., for signal processing). There are
versions available for different hardware platforms, and there are both professional and student
editions. When the MATLAB software is started, a window is opened: the main part is the
Command Window (see Figure 1.1). In the Command Window, there is a statement that says:
In the Command Window, you should see:
>>
The >> is called the prompt. In the Student Edition, the prompt
appears as: EDU>>
Figure 1.1 MATLAB Window
In the Command Window, MATLAB can be used interactively. At the prompt, any MATLAB
command or expression can be entered, and MATLAB will immediately respond with the result.
It is also possible to write programs in MATLAB, which are contained in script files or M-files.
There are several commands that can serve as an introduction to MATLAB and allow you to get
help:
info will display contact information for the product
demo has demos of several options in MATLAB
help will explain any command; help help will explain how help works

help browser opens a Help Window

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.

VARIABLES AND ASSIGNMENT STATEMENTS


In order to store a value in a MATLAB session, or in a program, a variable is used. The
Workspace Window shows variables that have been created. One easy way to create a variable is
to use an assignment statement. The format of an assignment statement is
variablename = expression

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:

 MATLAB has an wide-ranging on-line help system.


 MATLAB offers the help command
 By typing help in the command window, we can get help.
 The on-line help system of MATLAB allows the user to:
(i) Find exact description of commands.
(ii) Search for commands by name, category or keywords.
 Outside the MATLAB desktop, you can access on-line documentation from the
website:
 http://www.mathworks.com/help/matlab
 Type help win in the command prompt of MATLAB. This will display the MATLAB
help window. (>> help win)
MATLAR BAsics

Variables and donstants

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

The Stred value ls


set symbos .
two n e k
Commands create
RO Exmple: The fol l i n g Values 1 nd 3
Vaiebles named a a n d y that have the

respecively
a =

>Y= 3

Afther the irs-Command, MATLAB fs contitmin


That
it
t has Created a VMable called a and iven
the Value 1
The
-

hen We nter these commands ( i and V=3) intD


=

MATLAB bindon, the new Varíables i l appear in. the

WoKspace pane
-

Ustng these Varíables, , xpreSsions can e omed.


- For £9:

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

Names shold start ith a ieter, followes ky,


)
muliple letters digits oY underSeoves

rne
D MATLAB is case Sensihve (ie Upper Caselapltel)
LOerCaselSmall leters).

-Tn MAT LAB,+the Variable names and D represen t

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

name as 'MATLAB fnchios mme N2mes O


m a t c h oith
eNames variables shotld not
MATLAB functhons
MATLAB 2re Significant
the fArst 63 Characters 4-
ony

TommOn MATLABVariables
MOSt Ommon type MATLAB Vanabes re:
C)doble and i ) char

double:
that holds eal,
o Tt's a common MATLAB Variable

imaginary or complex Values


dotble-
Comsists Scalars or arras of 64-btt

Preasiom floaimg-point numbers.


numerical deta tupe tn
double is the prinipal(pasic)

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

real value 1o.5 to the double Variable.


assigns the

The faloroing Statement,


Var 4?
assigns he îmaginay Value 4 t o the double
Veriable Var
Char
ealare or
arrm
Tt is 2 Variable consishing
16-LIEaluee,
Each Varnable Yeprecerns a single charaCter.

singlecharacter r ) 2characer string


hene ler a
automaicaly
1S aSsigned to a Varisble n a m e , char is

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

This is a character Stringg


Comment

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

F r E9: a 6.+ (double type Variable)

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
-

Tt does not Change


FOY Example, constant TT = 3.1415.
built-in Variables a n d
-MATLAB has a u m b e r q
Contats.
in MATLAB a r e
Ome commany uSed
coNKt antts

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)

Not-a- Number (9,The


NaN vesultq Olo).

Doible precision repeesentahon


Pf Y2to TT
O1he Cimumterence

true and Represent logic Varïables

1ofici and logic 0.


false

lasterr a n d Returns h e Error and


Wa Yning mesSages received
astWam at he last ime.
Vectors and Matrices - Arrays:

ATray the fundamertal datatype în


MATLAB.

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

fip 2rray arr CTSTODimenSicnal)

eements in the array will be The


Tofal number
and the humber o
produuct the number roNS
COumns

Array Size

3x2 mamx,Contatnind 6 Elenerts


3
5 6
b 2 3 4 1x4 ar rry containvng 4élemen
(RO Vector),

3X) 2r2y
conteining 3 element,
(column Vector),
he Contenb the arry may be e d or modfied
t any time

Array oreratbr Zn MATLAB (on/ón

Array can be termed as a data object"dealing i t h


marices,
AYray operatioms:
term-by-term muliplicahon,

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

3s necessary or a iVen pYoblem.


Ys
Termed as a maYix CONSishng
be.
Array c n abo
ond OumnS

MATRIX boCk MATLAB


building in
the baeic
a
2Yranged
t is number
ement
1s Set
a
2nd Vertical
coumne
-Matrix roNS
anGlar rid
h o i ZNT2
rect
created
2l| The maiceS must be giher calle
or
- I n MATLAB,
WTThin 3 u a r e Brackets).
Y the Lser. TL iS SPeCiTied
C a n be xPressed Usn
-Linear taUations in MATLAB
matrix notation
and matrix algebra.

h e matríx
COmmands 2re
eome

Retume the
number o£lemens A
lengthA)
.Size[A)> ReTums he Size a marx A.

SizeA)>Returms the number YOKJS assigheå


. fYoN,o]=
to OK VaYiake ind coumns 3ssihel
o cumn variabe q A

- An array wih m rOS and m ciumns Called a marix


s i z e mxn.
Vector cales
ron or column, i t y
hen
n array has onlu ne

a VectoY
are c2lled as Vectors
1 - Dimencional arrays

For Example Vector WiTh


Here. X fs a Ons
X = Ci 2 3] fhvee f l e m e n t s

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,

The Uscr MATLAB can Write hís oKn tunchons.


once WYitten , these functiams behave just Jike the btuilt-in
funchons
Afunchon has a name and an argument în parentheses(BrakEs).

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

Some Common ly uSed 'Elementary MATLAB nmathemahcel

built-in funchons are given helon:


Table-L : Elementory math funcion s
Functim Descriphon Example
SrtB4)
Seyrt(x) Sauare root ans

> expl5)
exPCX) Exponential (e) ans -
148 4132
> abs(-24)
abs(x) Absolute Value ans E

Natural loqarihwm >log(1Ooo)


fogx) Base e loganthm(n) ns= 6.90t3

loqiox) Bose Lo l0garithm 101o(!O00)


ans=B:0000
factorial (x) The fac toria
ftunction !
factovial (5)
must bea Posi t ve
S
in tegr) 120.
Table-2 Tisoometic math Funchons

Funchion Deseriphon Exampe


Sine of argle >sin (P6)
SinCx) 1(7adianc ans. 5000
Coslx) Cosine Of anle > CosCPik)
( in rAdiansS) ans=
O 66O

tan (x) Tangert ef anfle tan(pis)


i n radians) ans Z
OS7+4-

Cot (x) cotangGent - angle ScotPVE)


ans E
( in Vodias)
11321

The inerse trigonmetric functhans are

as'n (x), acos(x) ,atan(x) and acotix) ,

The hyPerbolic trigonomeric funtions


Simhx),coshlx) , tanhx) and CothX),

Table-2 Rounding Punchons

Function DescrPtion Example


rOund (17/5)
round x) Ound to the mearest ns
tnteger
fixCx) Round toNadS fix(13/5)
zero. ans

Ceil (X) Round toWardS > ceil (!1/5)


nfinitY 3
floor(x) Round toWards >floor(-9/4)
minus (nfinity ans

rem(X,Y) Returns the temam >Tem(i3,5)


after ís dividea ns
by y.
Sgn(x) Sighlim-funchiom. >sígn(5)
RenuYns i F X>0, ans
Creating and psinting sinple plots
Table-4 string onversion FunchonS.

Functhon Description
ConvertS a mar*x of numbers intd a
chartx chaYacter string-

double(x) Converts a character string înto


2 matríx Of NUm bers.
int 2str x) Conyerts z into an inteser charzuter
stying
num2str(x) Comerts into a character string.

str2mumS) Converts character sting s into a


numeriC array

Notes Here x e Presents a Variable

ote: It's to be moted that, MATLAB funchions i11 automahically


calalate the Correct anser, een if the tesult is
magin ary or COmpex.

For X mple The functhon syrtl-2) il1 producea Vuntime


frror n lanrLages Such 2s C++,Java or FORTRAN.

MATLAB COTrectly c2lcculates the jmagmay answer, as


folloS
syrEC-2)

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.

To Plot a data Set, just create two vectors


Containing the and y values to be Plotted
When the plot funchion 1s £xecuted, MATLAB
Opens a fiqure Níndo0.
that hindon.
The Figure W*ndo displays the Plot in
The folloind MATLAB Cmmancs are uced tor
Creating,nam1nd and Printing símple plots
Command
Name Descrption
Plot C.reates a 2- D line Plot

xlabel Annotates the -axis.


CNaming of -2xiS) Sting:Nmel
ylabel Annotates the y-axiS. aminf
(Namin of y-axis) etstn
axis chandfes the aspect ratio Of the
axis and the y-axis.
title Puts a title on the plott.
CText string)

Print Prints a
hardeoPy O the Plot

grid Adds o emoves grid lines.


grid on
Tuyns-ON 9rid lines.
grid off Turns-OFF grid unes.
CYeating simple Plots
ASimPle Plot in MATLAB Ís a 2D (2-dimensianal)plot.
The basTc procedure for creating a MATLAB raph (Plot
is as follons;
e Take a vectorq1-coovdinates, X= (1,2 n).
SteP-2 Take a yectoY Y-ccOtdinates, y= (Y,,U2 9n).
oith i=1,2,-
Step-3
STep-3 Locate the points (i,U7)
srep-4: Join them by straight ines. PrePared a s

Its o be Kept in mind that, andy should be identical|


aYrayS
ABO, a n d y'are both Yow a r r a y s or column arrays of
the Same length

circle af unitradius for the Parametnc


Example; Draw 2

Equaton
cose, y= Sing O e < 21T

MATAB and print the output on Your


Lsing
SCreen.

Soluhon
Meth
data.
(1 Eist generate the
HereWe comSíder
- and y-co oYdinates of, say,

LoO Points on the cicle.

the COmmand: PlotiXY).


(2 Next, Plot the d a t a Using
3 pinally, Prmt fhe graph using printaommand.
We type the n
folloning program tditorwindon or

in the Command windon.


COmmenntS

>theta = linspace (o, 2 Pi, 1oo): r e ate a linearly


P R o 4 R A M

SPaced 100 -Elements


ong Vector e)
>X Costtheta) Ccalculate x-Cootdinata

>> y = sinltheta): (calculate y-coodnates)

Plot (x,Y) (plot x vs y)

> axfs ('equal (set the length scales


thO axes to be
O
the Same)
xlabel C'x') (-abel the 2-axis
t h X)
ylshel (Y') (Label the y-axis
srth Y)
i t l e (circle of unit radus') (Puts a title on the

Plot
Print
Print on the default
Printer.

The aboe program a s tuped on 'cemmand indonl sa:


Output ill be displayed in the Figure mdaN MATLAB
AesktoP
Example: Plot the vectrs x= (1,2,3,4,5 6) and Y=(3,-1,2,451)
to produce a picture

Soluton Tn the command (Prompt) Windon, l e type the


-follosing MATLAB coDE.
X=L1 2 3 4 5 6
Y [3 - i 2 4 1J:

> Plot (x, Y)


-output oil\ bc dispYed an the treen
OEhe default colour a MATLAB Plot (S Blue), other
ColoYS are also Possible,
SIMPLE PLOTSC2-0
Exercises
1) A simple sine plot;
Plot ySinZ, OLK 21T, taking Loo ineary Pace< ced
axes and put Plot
Points in the Gtven interval. Label the
CYeated by yourname" in the title,

n the £itor windan, We type the folloiNg ProGram:


x=linspace (0,2*pi,LOO);
Plot(x, inx))
xlabel('x')
ylabel (Y'
title
(Plot created by ch: Naveena')
Output ill be displaa m the Fíqure KoindN Ot

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

Plot(x, Ssin X), x, sinx), 'o)


xlabel Cx')
ylabel ('sino')

3) Space Cuve
civeular helix
Use the command plot3X,Y,z) to Plot the
- S t n t , ylt) = cOst, zlE) = E, O3E s20.

Ams: .TUpe he folloing proram in The eitor rdon of


MATLAB.

tiinspace (0,20, 100)


Plot 3(Stn(t),cost), t)
xercises (2-D plot
4)An fxPanetially decaying sine Plot:
plot y= e 4 s i n z , os 1 s 4TT, taking 1o,5o and 100 points

in the ínterval.

AS Tye the folloniná profram in MATLAB Editor iNdo

Xlinspace(0, 4*pi,1o): ith 1o points


Y exp-.4*x)."gin)
plot (xY)
X=lnSpce (o, 4*pi, 5o) Sth 5o Ppoints
y exp-4x).*stnx)
plot (x,yy)
X=lmspace (o, 4Pi, Lo6) % iTh Loo Points
Yexp(. 4x).*sin X)
plot(XY)
NOte Here 7 Saus, Commert Line.

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 .

+int: Frst Compute Ye X. 'a and then use semilogx(x,Y) sta|


AnS -The Plot commands semílogx, Semilogy and loglog
Plot the -Values, y-Values and both -and y
Value s n a oho seale.
Try/Type the following progyam in MATLAB Editor oino:

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

trstcUrve, uSe the holdon Command, and then Plot the


Second Curve on the of the first one.
top

Tupe the folloksing Profram in the MATLAB etorndn


X-linspace(0,Pi, 100):
Y CosCx);
Z 1-x.'2/2+x."4/24:
Plot (xY, X, z)
Plot (x,y, x, z,'--")
egend(cos cx), Z)
Creating, Savin and Eecuting a seript Ftle

-The ommands t e r e d in MATLAB commad HinddW


Cannot be saved
These commands Cannot be 5xecuted a6ain.

Therefore, 2 different hway is followed for


Executing h e Commands 1 t h MAT LAB,
Ttt 7s as folloNs;
iSt a Comm ands,
1 To ere ate a file h a

the fle, and


2 Save
3 run the file.
e
The files that ave used for this PUrpose
Called script files" or Scri ptS"

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.

Soripfiles have a filename Extension m They are

uSually talle a s , M-fIles .


M-ftles can be (a)seripts or functions.

The M-frle seripts Execute a eries o MATLAB


statements.
The M-file funChions ean accept artments ana
can prOduce one o r more Outputs.
SAVING Lxtensim to
The Script fi|e must be sal/ed wifh a m

its n2me.
Execut a t he2
by typing its
name
* SCYriptfile e r e u t e d
Commnd prompt.

Elitin and SaVng


Note I t s td be Noted that, ceating,
Files are Soneshat syaten-dependentt taskS-

(2) Creaing a ner) file

- On PCs and Macs -

MATLAB desktop Selec


From the file
menu of
File>NeN Blank M-File.

should appear
AneN edit (editor) +Sîndoh

on UN1X WoTKstations;

circle.m or lemacs circlesm at The


TypeVí
t o ogen a Editindog -in Vi or
MATLAB PYOmPt
emaCS.

EXomple; Drawa nit circle of unit radius Using the


Unit circle:
Parametric £auatim o a

COse, y-ine Oos21

Ans:-In the Blank M-f1le,type


the follooing Jlines;
% CIRCLE - A script file to dran 2 unft circle
*tere %
S i is Creae vector theta
theta - lîmspace (0,2pí, Loo)
Consideved
YJenerate -co-odne-
=CoS Ctheta)
comment
y=Sin (theta): generate Y- co.ordina
es

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.

d) A dialos box 3PpearS


doCument.
Type círcle»m as the name Of the
Save the file.
(JV) clicK Save to
Saved
Tts to be noted that, the frle should bee
in thefolder We tWat Tt to be, In
e Curvent NoY*ing folder /dire.cton af MATLAB.

C) Executing the file:


to MATLAB
-After Saying the file, qet back
desktop.
TO Axecute the scipt file, type The com mans

in he COmmand Ninda).

help circle
wnit circle.
Circle -A Script file to dr2N a

7 circle.

-Tf the Script l e is lre.ady opened in

MATLAB ai £ditor window e Can £xecute the


file oy PYessing the Run file icon
The F5tunchion Key stll 2ko taecute or Debug
the Script ftle.
Exercices
1) Shonthe center of the circle; c e n t e r ef
circle.m to show the
MOdty the script file center Point
*th a
too. shos the
The c i c l e on the plot,
'
Progrem
unit eirele
A Cript frle to daw
a
CIRCLE-

File Written by ch Naveen


a

theta = linspace (0, 2*PÍ,10O)


= Cos(theta);
Y Sinctheta):
plot (KY o,o,+);
axis ('equal );
tTtle (circle of unít radius)

Yadius of the circle,


2 chamge the dran a circle q avbiErary
MOdIfy the seript-file circle.m to
radius .

(Sol pocedue
-Fndlude the foloiin g Command
in the seri pt file
before the first Executable Jine Ctheta.

r inpub(enter the radius af the circle: ')


This wi11 ask the user to intut r ) on the screen.
Mod/y the - and y-Co.odinate calculabon.
Save and fxecute the file,
-hJhen asked, fnter a value for the radius
Press Yetur,

-The folloiing PrOfr>m con be itten tohange


the Yadius the Circle
Prodram:
CIRCLE- A Sript file to draN a eircle of raclius T
%Oriinal Circle.m file modified to introduce Variabe
r

Ftle written y ch:Naveena

T= Input (Enter the radiLS of the circle:")


Create Vector theba
theta =
lnspace(o, 2*pt, 1oo)
g e n e r a t e x-co.ordinates.
XY*cos(theta):
Y=r*sinCtheta); Generate y co.Ordinakes

plotY): plotthe circle

axiseaual);
ttle
7 Set £qual seale On sxes

(circle of given radfus r) put a


title.

2Vaviables Tn the orRspace:


-All variables created by a seript i l e wi11 be ShoNm
in the SoKSPace,
To the Variables
See Present in Your KOrKspace, tyre
the commend;
who.
Now, We See the esmmande} VaYi2bles r, theta, x an3 y
in the ist.
-TO get more tformation bout the Variables anl the
NorKSpce, tyPe the command
>>Whos.
To See the values o e,2 and y as three columns
type
theta x' y (tiheta' y' Y)
4Contents of the Rle:
- e can See the contents. of an M-f1le without

Openmg the file oith an £ditor


To display the contents, »tyre command 's used,
For Example;
ToSee the contents of circle.m, type: type circle:m
Command tn the command win doi

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

137 +3y+47 = 1 b=:1;


22+ 3y +3z = 2
XANb
Find the Solution to the
System of £quatons. Execution

I n the comn1and bne type;


Solutim
For findi soluthon, 1we, examplei
WYite the akoye Eowahons X

as matrices, în MATLAB, - 0.500bo


500O
-

Vsíng MATLAB editor, -05oOO


CYeate a neN M-file.
-
File> NeW> M-file. T's to be noted that fter
Execuhion, he Variables
Enter the statenments in he A,D and x remain in the
ftle Woykspace,
Save the ftle and Run the frlel
step 3
NOW Write anl Save the ffle unde the name circlefm»m

On Pes : Select SaVe AS. from the File menu.


A dialog box should appear
Type civelefn.m as the name of the docUment.
Save the ftle în the folder o u Want to.
click Save tO Save the File.

NOte:
TO Execute the funchion circlefn In tree different Ways
try the folloing:
R 5
> X,Y = cYclefn(R):

cx,cyl=circlefn (2 5); put S directly Specifie3.

> circle-fh (1):

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

Step-2 calclate the correspohdmg numbers Lsing he


fomule : Lm Pahrenhiet osy

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 tinitial: tpina Creabe a column VectoY G

F-1c 432 Compute, Correspondrkyl F


empt oble = [e F: Makea 2 coAm) matx O
nd F
Exercees
(ANote To convert celsfus to f2hrenhiet scale, the {omula
used is

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!.

/MATLAe Projr>m tD Compute n


funcion factn= facorial&)
PACTD RIAL : funchian to aompute factørial
. call Syrtax:
factn factonal (n);

facm = 1 Initiali ze also of

for = n -1:1L gefrom n to i

factn' factn*k %Mulidy n by n-1, n-2 £te.


end
PROGRAMMING BASTCS
ataypes
-
matrix.
în MATLAB 1S the array or
The basic data tyre
The basc data tyre in MATLAB i also called a class
The four fundanertal MATLAB data types ave.

double , ) lodical Gil) char 'and iv)function handles.


The O s t cOmmon MATLAB data tupes are shwn in

the higre bel.

MATLAB Data Types

ints, uts 1cal handes

Aaulesingte int16, uint16

int32, int 32
int 64, uint64

Cel stuture sses

urey MATLAB ÞataTypes.

a) double. and sngle


double and sinfle precision
\his type o d a t is stoied as
floatind point data.
Decimal nwnbers a e tepresentes byfloatní point data
types.
1o toe lhe
flozting point numbers,
Single Preciston occupies 4 byfes (2 bl&) and
(D dole recision oceupi 2 bytes(64 bita),
int8, înti6, înt32 and int64- [sige Ttefr yre
his type. data is sored a s intefers WThin shits,
16bits, a2bits and 64Lits respechively.
The bit countgives the Size The tnteferr
( ) uinta, uinti6, uint32 nd uint64 [Un simed Tnteer yre
Thipe data Stoves unsighed (dats înteser data
fn 3,16, 82 and 64 bits,

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.

-MATLAB s desigmed to opYate on matrices' and arrays

Using oReratorS, MATLAB fertorms Some elementary


Operanons.
Folloing are the typeslementary(operations)operatos
in MATLAB
() Arthmetic opelatvrs,
dt Relational operators.
Tr) togtc.al operators
CU) BitÖÍSE ORErators
VSet operators.
Aithmetic operators
These operators e Used tD
pextosm. aithmetic OPeraions
The basic Asthimete
oertrs in MATLAB ave han
beloo,
Symbol Role
Aiom
Sulstraction
uHi plicztion
Pvisiom
Matrix Perr
|Element nise
MutTPzion
Elemernt oicee
Riht pivision
emern Wise
POrer
Transpose.
Matix ttdisn
CBacksladh)
E ntise
Unary PluS
unary Mmus
bRelatiomal operators:
These ope rators are used to Show ertafn velahanship
beteen Variables.
There are six relatonal opextors în MATLAB They e

Smbol Role
Equal to

Not Gqual to
Greater than

Sreaterthan or Eual to
Les than

Less than or saual to

These Operators are feneralty uged n Conditianal statemen


Such as -then-eke branch
TO OYmore qhege operzdrs can abo.be(used] Combine.d
httn the help S logical operators

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.

-Theve are four osical operatvrs.

mbol Role

& logical AND


logical OR

loscal Compleotb
XOr exclusiVe OR

o6 ical AND/ Wth


crui ing)
Short-ciruihing
oical OR ET-ciruitind
ierarchy of oerations
The order in thich MATLAB ExPressions are eValuated
is termed as tierarchy of OPeratoms;
Jhe erations at tigher level , ve fValuated first.
Next, the operahons at Lover level are Avaluated

The huerarchy operatioms summarized in the


table shoon belmo

Precedene OeratiON

The Contents 2l Parantheses( )


ave evsluated.FlYst, the Contents
innermost pavan theses a r e
ENaluated. Nextthe Outwara
paranthe Ses are fvaluated

2 All exPonentals a r e fvaluated


They are valuated from 1eft to
sicht.
All multiplications and divisians
are evalusted
JOYKins from left
to vight.

All additions and subtractions


are tvaluated hbrking from lefE
to right.
hgureT>ble) Hiererchy cf Operztior

n MATLAB, the Operations are pertormed ba sed on the


"Operators
E T h e order i n whch the operators, in an xpression are Awaluae.d
s as ollois:
.All the arithmetic. Operators are £valuaked firat tn the odar
pveviousy deeibed.
2. All Yelaional operaturs (=, v=,>,>5 , <=) are £valuated
from 1eft to right. sorkinar
3, All Operators are, eyaluatedd.
4 All 4 and 4 operalurs are évaluated, Norntrmleft to r ght
5. Al 1,and xor Operaturs are fraluated, working trom left to right.
OpererwYS-Tmortant efinítions: C

Relatioal Operators
-

Relational oPerstors are


operators with tWo TUmerical or sfing
Operands
The Gener2l fom
Velational Operator iS

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

Here and 2 are ex Pressions a Variables, and dp is


one 1he logical operstor.
Loops, Branches and Control-flonw:

Pogrom confrol-flon
rogram control statementS are the Commands that
lter the. Sequential flaN a comruter Program.

Tn MATLAB, the Proáram contol statements are


( If b) for (c)Nhile and d) Sioitth
S m g these statements, the Execthon of oner more
prodvams can be 2ltered
MATLABs program control statemenb are dien belon:

Conditinal £xecuhon a t h i s is true do That.|


block ne r more statements

Unconditional multhple. xeLunon u this is


this is many bmes
for
for a bloCk Ome or more
do that.
statements
Condhonal mulhi pe £xecuthn |ihilethis 1strue
While Sa block dne or more
do that
Statementy.

Conditional tkecuion one do this if that is


Snitch block amoná severa 2lternah ve true o This 7f
blocks ne or more statements h a t is true "

Tf Statements (t, else, eselfen da)


-X X

-MATLAB ProNems often reUie, the use n command,


T h e yntax itstatemeat has three foms. they r e :
i f - n d structuve.(If-else -eNd struecture and
) f - elseif - else- end structur
The s L t x fo he above Thfee joms r e a s Shoon:

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 :

elseif (i1) 4(i==20)


K 51+j:
el se
Kzi,
end

USng the above. POam, logical branching for computations


fs provided.

Switch -Case statement 's


-Usinghe switch-cse, logical branching for computahons
Provided
is
The seneral eyntax
Switchflag
Case Valuet
Block1 computation

Case Value 2
block2 computatiom

otheroíse

ast block compitation

end

Vari2ble, Ao, block 1 computahn is pe me


el2g ís any
Here,
block 2 computatin is perfotmed
f flag=valueL ,

f fla: Valuez, and So o n ,


TAthe flaf Value doesnt
madh ny case, the last block
Computzion is Pefomed.

T h e Swtth Can be a numeric V>riable or a stuins Variole.


Example program usng a stin variable as the soltch:
coler 1n put ('color= ', 's'):
Stch cdor
case 'res'
c L o o]:
case geen
c Co o]
case 'blue
c Co o
1]:
otherise
error(fnvalid choice of colbr)
end.
While-end loop :

-A ohtle loop used to execube a statement erafroup


Statements for an indefinite number times
eveutedindehnite
The statementlgroup-tatements) are
hile
umber atimes until the Condition specified by
is no lonfer 3atiefed.

For ex>mple
proram for findin all poers 2 elaw loOco-
Vi
ume1

while num < 1o000


V-V num;
ii+1
Num2i
end
V display V

Syrt2x
while expression
code bloc'k

end

Hexe the controling tApregsion Produes a logical Value.

- f the Expressien is true, code block 1oil| be executes


APternard s, Cortrol ill rebum to hile statement
T the txpression iS talse, the profram ill Beaute the
fvst statement 2fter the end.
The break and Coninue Statements
-There are two addtional statements that can be used to coslthe
Operabiom of kwhile loops and for looPS.
They are the beak nd continue statements.

CaBreakK) break cSmnand/statement


-The break Statement teminates the execubovm a loP.
t Passes the control to he next statement at the end helop.
Tf a treak statenent s eacted n the body t h e loop, the
fxecchon athe body kOl| stop,
The Conto| HiIl| be transtered tothe first executable statement
after the loop.

Anxamle Profram qthe kreak_statemet in a.for loop S


as shoIn belos:

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.
-

Tf a continue statement is xecuted în the body alooP


the cuvent Pass thoough the looP otl| stop,
The contyol toil| Yetn to the
top qthe loop.
ample -the cotinue. statement in a for loop is Shon:
for 1 : 5

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

-Tts to be nosted that, the Continue. statemert Was


on the teration shen
xecutea
ii was 3.
The conol Was
ORtnot
tantered td the
topThe lod
xectinsthe
fprintstatemernt.

You might also like