Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

1

MA1LA8 kCGkAMMING
Spr|ntf WrlLe formaLLed daLa Lo sLrlng
SynLax
s errmsg sprlnLf(formaL A )
uescrlpLlon
s errmsg sprlnLf(formaL A ) formaLs Lhe daLa ln maLrlx A (and ln any addlLlonal maLrlx argumenLs) under conLrol of Lhe speclfled formaL sLrlng
and reLurns lL ln Lhe MA1LA8 sLrlng varlable s 1he sprlnLf funcLlon reLurns an error message sLrlng errmsg lf an error occurred errmsg ls an empLy
maLrlx lf no error occurred
sprlnLf ls Lhe same as fprlnLf excepL LhaL lL reLurns Lhe daLa ln a MA1LA8 sLrlng varlable raLher Lhan wrlLlng lL Lo a flle
rat rats
8aLlonal fracLlon approxlmaLlon
SynLax
raL(x)
uescrlpLlon
Lven Lhough all floaLlngpolnL numbers are raLlonal numbers lL ls someLlmes deslrable Lo approxlmaLe Lhem by slmple raLlonal numbers whlch are
fracLlons whose numeraLor and denomlnaLor are small lnLegers 1he raL funcLlon aLLempLs Lo do Lhls 8aLlonal approxlmaLlons are generaLed by
LruncaLlng conLlnued fracLlon expanslons 1he raLs funcLlon calls raL and reLurns sLrlngs
raL(x) wlLh no ouLpuL argumenLs slmply dlsplays Lhe conLlnued fracLlon
S raLs(x) reLurns Lhe same resulLs as Lhose prlnLed by MA1LA8 wlLh formaL raL
Cond|t|ona| Contro| |f sw|tch
1hls group of conLrol sLaLemenLs enables you Lo selecL aL runLlme whlch block of code ls execuLed 1o make Lhls selecLlon based on wheLher a
condlLlon ls Lrue or false use Lhe lf sLaLemenL (whlch may lnclude else or elself) 1o selecL from a number of posslble opLlons dependlng on Lhe
value of an expresslon use Lhe swlLch and case sLaLemenLs (whlch may lnclude oLherwlse)
lf else and elself
lf evaluaLes a loglcal expresslon and execuLes a group of sLaLemenLs based on Lhe value of Lhe expresslon ln lLs slmplesL form lLs synLax ls
lf loglcal_expresslon
sLaLemenLs
end
lf Lhe loglcal expresslon ls Lrue (LhaL ls lf lL evaluaLes Lo loglcal 1) Lhe MA1LA8 sofLware execuLes all Lhe sLaLemenLs beLween Lhe lf and end llnes
lL resumes execuLlon aL Lhe llne followlng Lhe end sLaLemenL lf Lhe condlLlon ls false (evaluaLes Lo loglcal 0) MA1LA8 sklps all Lhe sLaLemenLs
beLween Lhe lf and end llnes and resumes execuLlon aL Lhe llne followlng Lhe end sLaLemenL
?ou can nesL any number of lf sLaLemenLs
lf Lhe loglcal expresslon evaluaLes Lo a nonscalar value all Lhe elemenLs of Lhe argumenL musL be nonzero lor example assume x ls a maLrlx 1hen
Lhe sLaLemenL
1he else and elself sLaLemenLs furLher condlLlonallze Lhe lf sLaLemenL


* 1he else sLaLemenL has no loglcal condlLlon 1he sLaLemenLs assoclaLed wlLh lL execuLe lf Lhe precedlng lf (and posslbly elself condlLlon)
evaluaLes Lo loglcal 0 (false)
* 1he elself sLaLemenL has a loglcal condlLlon LhaL lL evaluaLes lf Lhe precedlng lf (and posslbly elself condlLlon) ls false 1he sLaLemenLs
assoclaLed wlLh lL execuLe lf lLs loglcal condlLlon evaluaLes Lo loglcal 1 (Lrue) ?ou can have mulLlple elself sLaLemenLs wlLhln an lf block
sw|tch case and otherw|se
swlLch execuLes cerLaln sLaLemenLs based on Lhe value of a varlable or expresslon lLs baslc form ls
swlLch expresslon (scalar or sLrlng)
case value1
sLaLemenLs LxecuLes lf expresslon ls value1
case value
sLaLemenLs LxecuLes lf expresslon ls value

oLherwlse
sLaLemenLs LxecuLes lf expresslon does noL
maLch any case
end
swlLch works by comparlng Lhe lnpuL expresslon Lo each case value lor numerlc expresslons a case sLaLemenL ls Lrue lf (valueexpresslon) lor
sLrlng expresslons a case sLaLemenL ls Lrue lf sLrcmp(valueexpresslon)
Loop Contro| for wh||e cont|nue break
WlLh loop conLrol sLaLemenLs you can repeaLedly execuLe a block of code looplng back Lhrough Lhe block whlle keeplng Lrack of each lLeraLlon
wlLh an lncremenLlng lndex varlable use Lhe for sLaLemenL Lo loop a speclflc number of Llmes 1he whlle sLaLemenL ls more sulLable for baslng Lhe
loop execuLlon on how long a condlLlon conLlnues Lo be Lrue or false 1he conLlnue and break sLaLemenLs glve you more conLrol on exlLlng Lhe loop
noLe ?ou can ofLen speed up Lhe execuLlon of MA1LA8 code by replaclng for and whlle loops wlLh vecLorlzed code See 1echnlques for
lmprovlng erformance for more lnformaLlon on Lhls
for
1he for loop execuLes a sLaLemenL or group of sLaLemenLs a predeLermlned number of Llmes lLs synLax ls
for lndex sLarLlncremenLend
sLaLemenLs
end
1he defaulL lncremenL ls 1 ?ou can speclfy any lncremenL lncludlng a negaLlve one lor poslLlve lndlces execuLlon LermlnaLes when Lhe value of
Lhe lndex exceeds Lhe end value for negaLlve lncremenLs lL LermlnaLes when Lhe lndex ls less Lhan Lhe end value
lor example Lhls loop execuLes flve Llmes
for n 6
x(n) * x(n 1)


end
seLs k equal Lo Lhe vecLor A(l) where l ls Lhe lLeraLlon number of Lhe loop lor Lhe flrsL loop lLeraLlon k ls equal Lo A(1) for Lhe second k ls equal
Lo A() and so on unLll k equals A(n) 1haL ls Lhe loop lLeraLes for a number of Llmes equal Lo Lhe number of columns ln A lor each lLeraLlon k ls
a vecLor conLalnlng one of Lhe columns of A
wh||e
1he whlle loop execuLes a sLaLemenL or group of sLaLemenLs repeaLedly as long as Lhe conLrolllng expresslon ls Lrue (1) lLs synLax ls
whlle expresslon
sLaLemenLs
end
lf Lhe expresslon evaluaLes Lo a maLrlx all lLs elemenLs musL be 1 for execuLlon Lo conLlnue 1o reduce a maLrlx Lo a scalar value use Lhe all and any
funcLlons
LxlL a whlle loop aL any Llme uslng Lhe break sLaLemenL
cont|nue
1he conLlnue sLaLemenL passes conLrol Lo Lhe nexL lLeraLlon of Lhe for or whlle loop ln whlch lL appears sklpplng any remalnlng sLaLemenLs ln Lhe
body of Lhe loop 1he same holds Lrue for conLlnue sLaLemenLs ln nesLed loops 1haL ls execuLlon conLlnues aL Lhe beglnnlng of Lhe loop ln whlch
Lhe conLlnue sLaLemenL was encounLered
8reak
1he break sLaLemenL LermlnaLes Lhe execuLlon of a for loop or whlle loop When a break sLaLemenL ls encounLered execuLlon conLlnues wlLh Lhe
nexL sLaLemenL ouLslde of Lhe loop ln nesLed loops break exlLs from Lhe lnnermosL loop only
return
AfLer a MA1LA8 funcLlon runs Lo compleLlon lL LermlnaLes and reLurns conLrol elLher Lo Lhe funcLlon LhaL called lL or Lo Lhe keyboard lf you need
Lo exlL a funcLlon prlor Lo Lhe polnL of normal compleLlon you can force an early LermlnaLlon uslng Lhe reLurn funcLlon reLurn lmmedlaLely
LermlnaLes Lhe currenL sequence of commands and exlLs Lhe currenLly runnlng funcLlon
reLurn ls also used Lo LermlnaLe keyboard mode
Ar|thmet|c operat|ons
MA1LA8 sofLware has Lwo dlfferenL Lypes of arlLhmeLlc operaLlons MaLrlx arlLhmeLlc operaLlons are deflned by Lhe rules of llnear algebra Array
arlLhmeLlc operaLlons are carrled ouL elemenL by elemenL and can be used wlLh mulLldlmenslonal arrays 1he perlod characLer () dlsLlngulshes Lhe
array operaLlons from Lhe maLrlx operaLlons Powever slnce Lhe maLrlx and array operaLlons are Lhe same for addlLlon and subLracLlon Lhe
characLer palrs + and are noL used
+ AddlLlon or unary plus A+8 adds A and 8 A and 8 musL have Lhe same slze unless one ls a scalar A scalar can be added Lo a maLrlx of any slze
SubLracLlon or unary mlnus A8 subLracLs 8 from A A and 8 musL have Lhe same slze unless one ls a scalar A scalar can be subLracLed from a
maLrlx of any slze
* MaLrlx mulLlpllcaLlon C A*8 ls Lhe llnear algebralc producL of Lhe maLrlces A and 8 More preclsely
lor nonscalar A and 8 Lhe number of columns of A musL equal Lhe number of rows of 8 A scalar can mulLlply a maLrlx of any slze
*Array mulLlpllcaLlon A*8 ls Lhe elemenLbyelemenL producL of Lhe arrays A and 8 A and 8 musL have Lhe same slze unless one of Lhem ls a
scalar


/Slash or maLrlx rlghL dlvlslon 8/A ls roughly Lhe same as 8*lnv(A) More preclsely 8/A (A8) See Lhe reference page for mrdlvlde for more
lnformaLlon
/Array rlghL dlvlslon A/8 ls Lhe maLrlx wlLh elemenLs A(l[)/8(l[) A and 8 musL have Lhe same slze unless one of Lhem ls a scalar
8ackslash or maLrlx lefL dlvlslon lf A ls a square maLrlx A8 ls roughly Lhe same as lnv(A)*8 excepL lL ls compuLed ln a dlfferenL way lf A ls an n
byn maLrlx and 8 ls a column vecLor wlLh n componenLs or a maLrlx wlLh several such columns Lhen x A8 ls Lhe soluLlon Lo Lhe equaLlon Ax 8
compuLed by Causslan ellmlnaLlon A warnlng message ls dlsplayed lf A ls badly scaled or nearly slngular See Lhe reference page for mldlvlde for
more lnformaLlon
Array lefL dlvlslon A8 ls Lhe maLrlx wlLh elemenLs 8(l[)/A(l[) A and 8 musL have Lhe same slze unless one of Lhem ls a scalar
MaLrlx power xp ls x Lo Lhe power p lf p ls a scalar lf p ls an lnLeger Lhe power ls compuLed by repeaLed squarlng lf Lhe lnLeger ls negaLlve x ls
lnverLed flrsL lor oLher values of p Lhe calculaLlon lnvolves elgenvalues and elgenvecLors such LhaL lf vu elg(x) Lhen xp v*up/v
lf x ls a scalar and ls a maLrlx x ls x ralsed Lo Lhe maLrlx power uslng elgenvalues and elgenvecLors x where x and are boLh maLrlces ls
an error
Array power A8 ls Lhe maLrlx wlLh elemenLs A(l[) Lo Lhe 8(l[) power A and 8 musL have Lhe same slze unless one of Lhem ls a scalar
MaLrlx Lranspose A ls Lhe llnear algebralc Lranspose of A lor complex maLrlces Lhls ls Lhe complex con[ugaLe Lranspose
Array Lranspose A ls Lhe array Lranspose of A lor complex maLrlces Lhls does noL lnvolve con[ugaLlon
ke|at|ona| Cperators
8elaLlonal operaLors compare operands quanLlLaLlvely uslng operaLors llke less Lhan and noL equal Lo 1he followlng Lable provldes a summary
lor more lnformaLlon see Lhe relaLlonal operaLors reference page
Less Lhan
Less Lhan or equal Lo
CreaLer Lhan
CreaLer Lhan or equal Lo
Lqual Lo
noL equal Lo
ke|at|ona| Cperators and Arrays
1he MA1LA8 relaLlonal operaLors compare correspondlng elemenLs of arrays wlLh equal dlmenslons 8elaLlonal operaLors always operaLe elemenL
byelemenL ln Lhls example Lhe resulLlng maLrlx shows where an elemenL of A ls equal Lo Lhe correspondlng elemenL of 8
A 7 69 0 3 03 6
8 8 7 0 3 1 7
Contro| I|ow Statements
8reak conLlnue for lf
1he condlLlons of an lf sLaLemenL cannoL use and | operaLors ln Lhelr place use Lhe and || operaLors respecLlvely 1o loglcally collapse
vecLors lnLo scalars use Lhe funcLlon all
8eLurn swlLch
1he behavlor maLches Lhe MA1LA8 swlLch sLaLemenL whlch execuLes only Lhe flrsL maLchlng case
3

whlle
1he condlLlons of whlle sLaLemenLs cannoL use and | operaLors ln Lhelr place use Lhe and || operaLors respecLlvely 1o loglcally collapse
vecLors lnLo scalars use Lhe funcLlon all
Log|ca| AND
1hls operaLor ls llmlLed Lo use ouLslde lf and whlle sLaLemenL condlLlons ln lLs place use Lhe operaLor 1o loglcally collapse vecLors lnLo
scalars use Lhe funcLlon all
|Loglcal C8
1hls | operaLor ls llmlLed Lo use ouLslde lf and whlle sLaLemenLs ln lLs place use Lhe || operaLor 1o loglcally collapse vecLors lnLo scalars use Lhe
funcLlon all
LlemenL complemenL
xor Loglcal excluslveC8
Loglcal Anu (shorLclrculLlng)
|| Loglcal C8 (shorLclrculLlng)
Syntax
clc
08.75t4n
clc clears all input and output Irom the Command Window display, giving you a "clean screen."
AIter using clc, you cannot use the scroll bar to see the history oI Iunctions, but you still can use the up arrow to recall statements Irom the
command history.
Syntax
clear all
08.75t4n
clear all clears all objects in the MATLAB workspace and closes the MuPAD engine associated with the MATLAB workspace resetting all its
assumptions.
Syntax
whos
whos(variables)
whos(location)
whos(variables,location)
s = whos(variables,location)
08.75t4n
whos lists in alphabetical order all variables in the currently active workspace, including their sizes and types.
whos(variables) lists only the speciIied variables.
6

whos(location) lists variables in the speciIied location: 'global' Ior the global workspace, or '-file' Ior a MAT-Iile. For MAT-Iiles, you
must also include the Iile name as an input.
whos(variables,location) lists the speciIied variables in the speciIied location. The location input can appear beIore or aIter
variables.
s = whos(variables,location) stores inIormation about the variables in structure s. SpeciIying variables and location is optional.
Syntax
str = num2str()
str = num2str(, 5recision)
str = num2str(, 1ormat)
08.75t4n
The num2str Iunction converts numbers to their string representations. This Iunction is useIul Ior labeling and titling plots with numeric values.
str = num2str() converts array into a string representation str. Converted Iloating-point values have a maximum oI Iour digits oI
precision, and an exponent iI required. For integer values, num2str returns the exact string representation oI the value.
str = num2str(, 5recision) converts the array into a string representation str with the maximum number oI digits speciIied by
5recision.
str = num2str(, 1ormat) converts array using the supplied 1ormat, as described on the fprintf Iunction reIerence page. By deIault,
num2str displays Iloating point values using the '%11.4g' Iormat (Iour signiIicant digits in exponential or Iixed-point notation, whichever is
shorter).
S50.al Valu08
Several Iunctions return important special values that you can use in your own program Iiles.
ans-Most recent answer (variable). II you do not assign an output variable to an expression, MATLAB automatically stores the result in ans.
eps-Floating-point relative accuracy. This is the tolerance the MATLAB soItware uses in its calculations.
pi=3.1415926535897...
i, jImaginary unit.
infInIinity. Calculations like n/0, where n is any nonzero real value, result in inf.
disp - Display text or array
Syntax
/isp(X)
08.75t4n
/isp(X) displays an array, without printing the array name. II X contains a text string, the string is displayed.
Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable.
The /isp Iunction accepts only one input. To display more than one array or string, you can use concatenation or the sprintf or fprintf
Iunctions as shown in
7

sprintf - Format data into string
Syntax
str = sprintf(1ormat, , ...)
08.75t4n
str = sprintf(1ormat, , ...) applies the 1ormat to all elements oI array and any additional array arguments in column order, and
returns the results to string str.
Uolon {:] - Create veUtors, array subsUripting, and 147-loop iterators
08.75t4n
The colon is one oI the most useIul operators in MATLAB. It can create vectors, subscript arrays, and speciIy for iterations.
The colon operator uses the Iollowing rules to create regularly spaced vectors Ior scalar values i, j, and k:
j:k is the same as j,j+1,...,k,, or empty when j k.

II you speciIy nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).
You can use the colon to create a vector oI indices to select rows, columns, or elements oI arrays, where:
A(:,j) is the jth column oI A.
A(i,:) is the ith row oI A.
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
A(j:k) is A(j), A(j+1),...,A(k).
A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).
A(:,:,k) is the kth page oI three-dimensional array A.


input - Request user input
Syntax
evalRes5onse = input(5rom5t)
strRes5onse = input(5rom5t, 's')
08.75t4n
evalRes5onse = input(5rom5t) displays the 5rom5t string on the screen, waits Ior input Irom the keyboard, evaluates any expressions in
the input, and returns the value in evalRes5onse. To evaluate expressions, the input Iunction accesses variables in the current workspace.
strRes5onse = input(5rom5t, 's') returns the entered text as a MATLAB string, without evaluating expressions.
Use these Iormat types to aIIect the spacing in the display oI all variables.
8

Valu0 f47 ty50 R08ult Exam5l0
compact Suppresses excess line Ieeds to show more output in a single screen. Contrast with loose. theta = pi/2
theta =
1.5708
loose Adds lineIeeds to make output more readable. Contrast with compact. theta = pi/2

theta =

1.5708
menu - Cenerate menu of UoiUes for user input
Syntax
choice = menu('mtitle','opt1','opt2',...,'optn')
choice = menu('mtitle',options)
08.75t4n
choice = menu('mtitle','opt1','opt2',...,'optn') displays the menu whose title is in the string variable 'mtitle' and whose
choices are string variables 'opt1', 'opt2', and so on. The menu opens in a modal dialog box. menu returns the number oI the selected menu
item, or 0 iI the user clicks the close button on the window.
choice = menu('mtitle',options) , where options is a 1-by-N cell array oI strings containing the menu choices.
II the user's terminal provides a graphics capability, menu displays the menu items as push buttons in a Iigure window (Example 1). Otherwise. they
will be given as a numbered list in the Command Window (Example 2).
4ndt4nal Stat0m0nt8
Conditional statements enable you to select at run time which block oI code to execute. The simplest conditional statement is an if statemen
gUd - Createst Uommon divisor
Syntax
= gc/(A,B)
,C,D, = gc/(A,B)
08.75t4n
= gc/(A,B) returns an array containing the greatest common divisors oI the corresponding elements oI integer arrays A and B. By convention,
gc/(0,0) returns a value oI 0; all other inputs return positive integers Ior .
floor - Round toward negative infinity
Syntax
B = floor(A)
B = floor(A) rounds the elements oI A to the nearest integers less than or equal to A. For complex A, the imaginary and real parts are rounded
independently.
Exam5l08
9

a = -1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i,


floor(a)

ans =

-2.0000 -1.0000 3.0000 5.0000

7.0000 2.0000 + 3.0000i
mod - Modulus after division
Syntax
= mo/(X,Y)
08.75t4n
= mo/(X,Y) iI Y ~= 0, returns X - n.Y where n = floor(X./Y). II Y is not an integer and the quotient X./Y is within roundoII error
oI an integer, then n is that integer. The inputs X and Y must be real arrays oI the same size, or real scalars.
wile - Repeatedly exeUute statements wile Uondition is true
Syntax
while ex5ression
statements
en/
08.75t4n
while ex5ression, statements, en/ repeatedly executes one or more MATLAB program statements in a loop as long as an
expression remains true.
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is
Ialse.
Expressions can include relational operators (such as or ==) and logical operators (such as &&, ||, or ~). MATLAB evaluates compound
expressions Irom leIt to right, adhering to operator precedence rules.
Rules for Variable Names
Although variable names can be oI any length, MATLAB uses only the Iirst N characters oI the name, (where N is the number returned by the
Iunction namelengthmax), and ignores the rest. Hence, it is important to make each variable name unique in the Iirst N characters to enable
MATLAB to distinguish variables. Also note that variable names are case sensitive.
Making Sure Variable Names Are Valid
BeIore using a new variable name, you can check to see iI it is valid with the isvarname Iunction. Note that isvarname does not consider names
longer than namelengthmax characters to be valid.
For example, the Iollowing name cannot be used Ior a variable since it begins with a number.
isvarname 8thColumn
ans =
0
10

Do Not Use FunUtion Names for Variables
When naming a variable, make sure you are not using a name that is already used as a Iunction name. II you do deIine a variable with a Iunction
name, you will not be able to call that Iunction until you clear the variable Irom memory. (II it is a MATLAB built-in Iunction, then you will still
be able to call that Iunction but you must do so using builtin.)
To test whether a proposed variable name is already used as a Iunction name, use
which -all name
CeUking for Reserved Keywords
MATLAB reserves certain keywords Ior its own use and does not allow you to override them. Attempts to use these words may result in any one oI a
number oI error messages, some oI which are shown here:
Avoid Using i and | for Variables
Avoid Uverwriting Variables in SUripts
MATLAB scripts store their variables in a workspace that is shared with the caller oI the script. When called Irom the command line, they share the
base workspace. When called Irom a Iunction, they share that Iunction's workspace. II you run a script that alters a variable that already exists in the
caller's workspace, that variable is overwritten by the script.
Persistent Variables
To get the equivalent oI a static variable in MATLAB, use persistent. When you declare a variable to be persistent within a Iunction, its
value is retained in memory between calls to that Iunction. Unlike global variables, persistent variables are known only to the Iunction in
which they are declared.
ProteUting Persistent Variables
You can inadvertently clear persistent variables Irom memory by either modiIying the Iunction in which the variables are deIined, or by
clearing the Iunction with one oI the Iollowing commands:
clear all
clear functions
Clobal Variables
Use global variables sparingly. The global workspace is shared by all oI your Iunctions and also by your interactive MATLAB session. The more
global variables you use, the greater the chances oI unintentionally reusing a variable name, thus leaving yourselI open to having those variables
change in value unexpectedly. This can be a diIIicult bug to track down.
Viewing Variables in a MAT-File
To see what variables are saved in a MAT-Iile, use who or whos as shown here (the .mat extension is not required). who returns a cell array and
whos returns a structure array.

You might also like