You are on page 1of 99

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 1



BASIC MATLAB CONCEPTS
1.1. Introduction to MATLAB
At the end of this lesson, the student shall be able to understand MATLAB capabilities and uses, as well as
the toolboxes associated with it.
MATLAB is developed and published by MathWors, a leadin! developer and supplier of technical
co"putin! software in the world. #ounded in 1$%&, the co"pany e"ploys over '((( people worldwide. The
co"pany is privately held and has been profitable every year since its inception. Its head)uarters is located
in *atic, Massachusetts, +,. -ther "a.or product released by the co"pany is the ,i"ulin, a data flow
!raphical pro!ra""in! lan!ua!e tool for "odelin!, si"ulatin! and analy/in! "ulti0do"ain dyna"ic
syste"s. MathWors website is at www."athwors.co".
MathWors was founded by 1ac Little 2current 3resident and 45-6, 4leve Moler 24hief ,cientist6 and
,teve Ban!ert 2now inactive6. Its first custo"er was the Massachusetts Institute of Technolo!y 2MIT6. The
year 1$$7 saw the co"pany8s !lobal expansion by establishin! offices outside the +,. In '(1', the
co"pany8s revenue stood at +,9 7:( "illion, with "ore than ;(< of it co"in! outside the +,.
MATLAB, the lan!ua!e of technical co"putin!, is a pro!ra""in! environ"ent for al!orith" develop"ent,
data analysis, visuali/ation and nu"eric co"putation. The followin! are the ey characteristics of the
MATLAB lan!ua!e=
A user0friendly, intuitive syntax favorin! brevity and si"plicity without co"pro"isin! intelli!ibility>
The hi!hest )uality nu"erical al!orith"s, based on close historical ties with the nu"erical analysis
research co""unity>
3owerful, easy0to0use !raphics and visuali/ation capabilities>
A hi!h0level lan!ua!e, "ain! it possible to carry out co"putations in a line or two that would
re)uire hundreds of lines of code in other "athe"atical lan!ua!es>
5asy extensibility, by the user or via paca!es of application0specific MATLAB code and ?+Is
nown as toolboxes>
@eal and co"plex vectors and "atrices 2includin! sparse "atrices6 as funda"ental data types.
The fi!ure below shows the whole fa"ily of products released by MathWors, as well as the applications to
which these products are used. The software extensions of MATLAB and ,i"ulin for specific applications
are called toolboxes. The picture was taen fro" the website of MathWors.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 2


Figure 1. 1 MathWorks' family of products and applications.
To have an appreciation of the use of MATLAB and other products, watch the followin! video fro" the
MathWors website= http=AAwww."athwors.co"Atechnical0co"putin!A.
The followin! industries have been usin! MathWors products for the past years=
aerospace and defense>
auto"otive>
biotechnolo!y, "edical and phar"aceutical>
che"ical and petroleu">
co"puters and office e)uip"ent>
education>
electronics and se"iconductors>
finance and econo"ics>
!overn"ent>
industrial e)uip"ent and "achinery>
instru"entation>
"arine>
si!nal processin! and co""unications> and
utilities and ener!y.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 3

What basically can you do with MATLABB Watch the followin! video=
http=AAwww."athwors.co"AvideosA"atlab0overview0;1$'C.ht"lBtypeDshadow.
Drill Problem 1.1
1. ,earch on the MathWors website to find out what toolboxes are included in the MATLAB and ,i"ulin
fa"ily of products, as well as those under their application areas. Mae a list under each cate!ory and write
down the purpose of each.
'. The uses of MATLAB were de"onstrated in the first video shown. Write your own thou!hts about how
can MATLAB be used based on that video.
C. -n the second video, the capabilities of MATLAB are described. 5nu"erate these.
&. *arrate on how you thin MATLAB can help you in your develop"ent as an en!ineer.

1.'. The MATLAB environ"ent
At the end of this lesson, the student shall be able to=
a. start the MATLAB pro!ra", identify, "anipulate and use the various MATLAB windows>
b. !enerate and edit scalars, vectors and "atrices>
c. perfor" si"ple arith"etic operations on scalars, vectors and "atrices>
d. ad.ust the for"at used to display nu"bers in the co""and window>
e. save the value of variables used in MATLAB>
f. save a series of co""ands in an "0file> and
!. solve si"ple "athe"atical proble"s usin! MATLAB.
To start MATLAB, double0clic on the icon of MATLAB on the destop or access it thru the ,tart button of
Windows 2Windows7 or Windows E36. The icon for MATLAB is shown below.

Figure 1. 2. MATLAB icon
When opened, the default MATLAB destop loos lie the one shown in fi!ure 1.C.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 4


Figure 1. . The default MATLAB en!ironment.
There are four windows in the default MATLAB destop=
The current folder window, with a details pane below it, shows the files that are contained in the
current folder bein! accessed by MATLAB. The details pane below it describes or previews the file
if applicable.
The co""and window is where co""ands to MATLAB are sent and results are returned. The
co""and pro"pt >> si!nifies a line of co""and.
The worspace window displays the variables that are bein! used in the MATLAB destop, as well
as the details of these variables such as its value, data type, etc. The window also contains a
dropdown "enu of plottin! options for variables stored in it.
The co""and history window which eeps a lo! of all the previous co""ands sent via the
co""and window.
The current folder location displays the location of the current folder opened within the MATLAB
environ"ent. When accessin! files within the MATLAB environ"ent, this location should point to the
location of the files.
+nlie the previous versions of MATLAB, the environ"ent of the @'(1Ca version does not feature the start
button. Instead, a ribbon0type "enu which displays all available "enu ite"s for a particular cate!ory is
used.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 5

5ach of the windows of the default MATLAB environ"ent is undocable. 1ust clic on the pulldown icon to
display the options for the window

Figure 1. ". #ndocking MATLAB $indo$.
When undoced, it can be doced a!ain inside the MATLAB window by clicin! the pull down "enu and
choosin! Dock option in the "enu.

Figure 1. %. &ocking 'ack MATLAB $indo$.
1ust lie any applications, each window of the MATLAB, as well as the MATLAB window itself can be
"ini"i/ed, "axi"i/ed or resi/ed.
The command window and the command hitor! window. As the discussions pro!ress, the use of each
windows in the MATLAB environ"ent will be de"onstrated. #or now, let us si"ply use the MATLAB
co""and window. As stated before, the co""and window is where co""ands to the MATLAB are sent
and results displayed. Fou can perfor" calculations on the co""and window as you would on a scientific
calculator. #or exa"ple, enter the co""and

and the followin! result will display
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 6


-r, to find the value of cos , type in

and the result is displayed as 1.
4o""ands in the MATLAB co""and window cannot be undone or uncreated. Gowever, they can be
repeated. The co""and history window shows you the co""ands you have typed in the co""and
window. Fou can recall it fro" there. Alternatively, you can press the +p or 9own arrow of your eyboard to
recall the previous co""ands sent to the co""and window.
E"am#le 1.1
Type the followin! co""ands into the MATLAB and write down the results.
1. 5 + 2
'. 5 * 2
C. 5/2
&. 3 + 2*(4+3)
:. 2.54*8/2.6
;. 6.3 2.1045
7. 3.6^2
%. 1 + 2^2
$. sqrt(5)
1(. cos(pi)

The co""and clc clears the co""and window of everythin!. To clear the co""and history window,
ri!ht0clic on the title bar of the co""and history window to display various short0cut "enus and choose
Clear Command $itor!, as shown in fi!ure 1.;.

Figure 1. ( )learing the command history $indo$.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 7

The work#ace. *otice in the worspace window that as you type the co""ands in the exa"ple, there
appears an ite" as shown below. 2*ote= there "i!ht be sli!ht discrepancies with the display of the
worspace, dependin! on how MATLAB is installed and its version.6

Figure 1. *. The current $orkspace $indo$.
The na"e ans is called a variable and it is the default variable that holds the value of the results of the
co""ands executed in the co""and window. These results can be placed onto other variable na"es. #or
exa"ple type in

and notice that the variable x now appears on the worspace window, as shown below.

Figure 1. +. The $orkspace after entering the last command.
,et the worspace to show "ore about the displayed variables by ri!ht0clicin! on the bar with the colu"n
labels. 4hec B!te and Cla and unchec the Min and Ma" ite"s. Four worspace should so"ehow
loo lie the one shown in fi!ure 1.$.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 8


Figure 1. ,. The $orkspace $ith the si-e. 'ytes and class information displayed.
The yellow, !rid0lie sy"bol indicates that the variable beside it is a nu"erical array. The si/e, 10by01
indicates that it is a scalar value 2an array with a one row and one colu"n6. The bytes colu"n indicates that
the variable occupies % bytes of "e"ory 2e)ual to ;& bits of data6. Lastly, the class colu"n indicates that
the variable is a double precision floatin!0point nu"ber.
?oin! bac to the previous co""and you sent to MATLAB

always re"e"ber that MATLAB evaluates first the ri!ht0hand expression and then stores or assi!ns the
result in the variable na"ed x. This is not the left0hand side is e)ual to the ri!ht0hand side. A co""and
such as this is an assi!n"ent co""and> it assi!ns the value of the ri!ht0hand expression and assi!ns it to
the left0hand expression. Thus the sy"bol = does not "ean His e)ual toI in MATLAB but rather it His
assi!ned toI.
Tae note that MATLAB also displays the i""ediate results of the co""ands you entered. Fou can
suppress the display of the results by ter"inatin! a co""and with a se"i0colon ; such as

Jariable na"es in MATLAB are case0sensitive, that is the variable x is different fro" X. -nly alphanu"eric
characters, and the underscore character are allowed to be used as variable na"es. The co""and
isvarname deter"ines whether a variable na"e is valid or not, #or exa"ple, the co""and

is a valid variable na"e 2a lo!ical 1 "eans true6 while the variable na"e
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 9


is not a valid variable na"e 2a lo!ical 0 "eans false6. Tae note of the sy"bol used by MATLAB to
represent lo!ical 2Boolean6 values in the worspace.
Also, MATLAB only reco!ni/es the first ;C characters of the variable na"e used. When you assi!n another
value to a variable that is already on the worspace, its value is overwritten with the new one. MATLAB
also uses set of eywords which cannot be used as variable na"e. To now all of these eywords type the
co""and

Fou can test whether or not a variable na"e is a eyword or not. Type in

which "eans that the variable na"e TimeFrame is not a eyword.


Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 10

#or exa"ple, type in the co""and

and MATLAB returns an error. Built0in functions in MATLAB can be used as variable na"es, however. #or
exa"ple, the sin() 2sine6 function co"putes the sine of its ar!u"ent. But it can be used as a variable
na"e, as in

but when used as a function

returns an incorrect infor"ation. The co""and which deter"ines whether a set of characters is used as
variable or a built0in function or eyword. In this case, typin! in

returns that sin is a variable. It can be restored as a function by clearin! it fro" worspace. Fou can clear
a specific variable if you type clear <variable_name>. The co""and clear clears all the
variables in the worspace. Thus the co""and

clears sin fro" the worspace and typin! in

displays that sin is now a built0in function.
The co""and whos displays all the variables in the worspace as well as so"e infor"ation about the
variables.
The c%rrent &older window and the c%rrent &older location. The current folder window displays the
folders and files located at the location pointed by the current folder directory. #or exa"ple, download the
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 11

folder H'a#riceI fro" the #T3 and paste in on the destop of your co"puters. Then locate this folder on
your MATLAB directory as shown in fi!ure 1.1(.

Figure 1. 1/. The current folder $indo$ after setting the MATLAB directory to the location of gasprices folder.
3ull up the 9etails pane to view the details about the file selected in the current folder window.

Figure 1. 11. The current folder $indo$ and the details pane.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 12

E"am#le 1.(
Test the followin! variable na"es in MATLAB usin! the co""ands isvarname, iskeyword and
which and co""ent on the results.
1. test
'. Test
C. if
&. my-book
:. my_book
;. Thisisoneverylongnamebutisitstillallowed?
7. 1stgroup
%. group_one
$. zzaAbc
1(. z34wAwy?12#
11. sin
1'. log

Scalar) *ector) and Matrice. In MATLAB, an n0di"ensional nu"erical array 2whether real or co"plex6
is a funda"ental data type, so definin! the" is a very si"ple tas. MATLAB allows for entries for the
followin!=
scalars which are 1 1 nu"erical array>
vectors which are one0di"ensional array> can be a row vector 21 n array6 or a colu"n vector
2n 16 array>
"atrices which are two0di"ensional m n array> and
hi!her0order n0di"ensional arrays.
In this topic, we cover the first three types. There are basically four ways to input data into MATLAB,
na"ely=
entered by an explicit list of ele"ents>
!enerated by built0in state"ent and functions>
created by "0files 2MATLAB scripts6> and
loaded fro" external data.
The co""and

creates a scalar of value S assi!ned to variable a. The row vector
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 13

b = |
1 2 S 4 S
]
is entered usin! the co""and

while the colu"n vector
c =
l
l
l
l
l
1
2
S
4
S
1
1
1
1
1

can be entered in MATLAB usin! the co""and

The "atrix
A = _
1 2 S 4
1 S 4 u
6 S 1 2
4 7 u 2
_
can be entered in MATLAB usin! the co""and

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 14

In definin! vectors and "atrices, the concatenation operator []2s)uare bracets6 are used. 4olu"n
ele"ents are separated by white spaces 2sin!le space or tab space6 and rows are created usin! se"i0
colon ;.
Jectors and "atrices can also be !enerated usin! built0in state"ents and functions. An exa"ple is the
!eneration of vectors with ele"ents unifor"ly spaced over a !iven interval. To !enerate the row vector
u = |
1 2 S 4 S 6 7 8 9 1u
]
which is a row vector with 1 as the first ele"ent, 1u as the last ele"ent, and unifor"ly spaced by 1 unit
per ele"ent, use the co""and

To !enerate vectors with intervals other than 1, use the co""and

or

To !enerate a colu"n vector with unifor" spacin!, use the sin!le )uote transpose operator as in
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 15


The function linspace() can also !enerate a unifor"ly spaced row or colu"n vector within a !iven
interval. Gowever, it re)uires the si/e of the vector to be specified. #or exa"ple, to !enerate a row vector
fro" 1 to 1u with 2u ele"ents, use the co""and

To !enerate lo!arith"ically spaced vectors, use the logspace()co""and. The first two values of the
ar!u"ent are the powers of ten representin! the initial and final values in the array. The final value is the
nu"ber of ele"ents in the array. Thus

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 16

Jectors or "atrices of ones and /eros can be easily !enerated in MATLAB. The function ones(m,n)
and zeros(m,n) !enerates m n "atrix whose ele"ents are all 18s or u8s respectively. Thus, the
co""and

!enerates a row vector of 18s,

!enerates a colu"n vector of /eros, and

!enerates a S 4 "atrix of 18s. Matrices can also be concatenated with other "atrices #or exa"ple, the
co""and
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 17


vertically concatenates "atrices A and B vertically. The co""and

hori/ontally concatenates "atrix A and the transpose of B. *ote that for concatenations to be accepted by
MATLAB, the di"ensions of the "atrices to be concatenated should be consistent 2i.e., e)ual nu"ber of
rows for hori/ontal concatenation, e)ual nu"ber of colu"ns for vertical concatenation6.
-ther built0in and user0defined 2with the use of MATLAB scripts or "0files6 special "atrix !enerators will be
discussed on the succeedin! lessons.
#inally, data can be i"ported into MATLAB fro" external data source such as M, 5xcel files, co""a0
separated values 24,Js6, audio, i"a!es, video and real0ti"e data. #or exa"ple, to load the M, 5xcel file
H'a#rice."lI into MATLAB, locate the file first on the MATLAB directory until it displays in the current
folder window. Then double0clic on the H'a#rice."lI to initiate the I"port 9ata Wi/ard. MATLAB will
auto"atically select the nu"erical data in the file. This is sufficient for now> we will deal with non0nu"erical
data later on. I"port the data as a Matri", and then clic on the Im#ort Selection as shown in fi!ure 1.1'.
A notice will pop0out that a 19 11 "atrix na"ed gasprices has been i"ported in MATLAB. Jerify
this by typin! the variable na"e on the co""and window.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 18


Figure 1. 12. The 0mport &ata Wi-ard.
To edit variables, either re0assi!n new values on the variable na"e to overwrite it or use the variable editor.
#or exa"ple, to chan!e the values of the variable b already assi!ned and defined at the worspace, type
in the co""and

and b is now reassi!ned with a new value. The variable editor can be initiated by double0clicin! the
variable in the worspace. Try this with the gasprices data. The variable editor loos and wors lie
your spreadsheet editor. @eplace the cell with the NaN entry 2first row, second colu"n6 with the value
2.96. When you press the 5nter ey, the new value is auto"atically saved in the gasprices data.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 19


Figure 1. 1. The !aria'le editor.
E"am#le 1.+
4lear all the variables in the worspace of MATLAB and then define the followin! scalars, vectors and
"atrices. +se as "any different approaches as possible.
1. a = 6.u22 1u
23

'. b = 1.6u2 1u
-19

C. c = |
1 u 4 S
]
&. u =
l
l
l
l
l
l
l
1u
9.99
9.98

9.98
9.99
1u
1
1
1
1
1
1
1

:. A =
l
l
l
l
l
l
l
l
1
1
2
1
3
1
4
1
5
1
2
1
3
1
4
1
5
1
6
1
3
1
4
1
5
1
6
1
7
1
4
1
5
1
6
1
7
1
8
1
5
1
6
1
7
1
8
1
9
1
1
1
1
1
1
1
1
. Matrix A is a S S Gilbert "atrix, a "atrix widely used in approxi"ation
theory.
;. B = _
2 4 7 S
u 1 1 S
1 2 S 4
7 4 S u
_
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 20

7. C = _
2 4 7 S 1
u 1 1 S u
1 2 S 4 4
7 4 S u S
_. *otice that "atrix C is the au!"ented "atrices B and the row
vector c.
%. e = |u u u u u u u u u u 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
$. A 1u 1u identity "atrix B. An identity "atrix is a "atrix whose "ain dia!onal ele"ents are all
ones and the rest are /eros.
1(. In H'a#rice."lI, create a 19 2 "atrix of the !as prices in Mexico. The first colu"n of the
"atrix contains the Fear data, while the second colu"n contains the data of the !as prices in
Mexico. 4all this "atrix Mexico, and your "atrix should loo lie this


Baic MATLAB o#eration on calar. The table below su""ari/es the arith"etic operations between
two scalars.
Ta'le 1. 1. MATLAB arithmetic operators for scalar !alues 1Moore. 2/122.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 21

The co""and

adds two scalar values. MATLAB can also operate on values assi!ned on variables defined in worspace,
such as

As stated before, the e)ual si!n in MATLAB is an assi!n"ent operator. As such, the expression

will "ae sense in MATLAB, unlie if it is interpreted as an al!ebraic expression. The latter expression
"eans Hthe value of y plus 1 is assi!ned to the variable yI, the result returnin! 11 and is assi!ned to the
variable y. -perations in MATLAB follow the standard al!ebraic order of precedence, that is=
-perations inside the parentheses are perfor"ed first, worin! fro" inner"ost set to the
outer"ost>
5xponentiation operation are perfor"ed next>
Multiplication and division operations are perfor"ed fro" left to ri!ht>
Addition and subtraction operations are perfor"ed fro" left to ri!ht.
#or exa"ple, to evaluate the for"ula
SA = 2i
2
+ 2ih = 2i(i + h)
with i = S and h = 1u, one can for"ulate the co""ands in MATLAB as

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 22


or

If one for!ets the parenthesis, the results will be

because MATLAB would perfor" the "ultiplications fro" left to ri!ht first, and then will add the value of h
to the results. If instead it was the "ultiplication operator before the r+h ter" that was for!otten instead of
the parenthesis,

the co""and will return an error. Fou should be very careful when translatin! your for"ulas into MATLAB
expressions. +se extra parenthesis whenever possible for your and your readers8 convenience. Another
way to "ae readable co""ands and codes is to brea expression into parts. 4onsider the expression
f =
log(ax
2
+ bx + c) sin(ax
2
+ bx + c)
4x
2
+ cos(x 2) - (ax
2
+ bx +c)

The evaluation of this expression can be easily perfor"ed by first definin! the values for the variables,

and then definin! the repeatin! polyno"ial ax
2
+ bx + c and the deno"inator

and finally evaluatin! f usin! the previously defined variables
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 23


E"am#le 1.,
3redict the output of the followin! expressions and then create MATLAB syntax for each. Jerify if the
results of MATLAB are consistent with your predictions.
1. 66 + S
'. 2 - 6^2
C. (S + S) - 2
&. S + S - 2
:. 4 - S2 - 8
;. S 24 +6^2
7. 2^S^4
%. 2^(S^4)
$. S^S + 2
1(. S^(S + 2)

4reate and test MATLAB syntax to evaluate the followin! expressions, then chec your answers with a
handheld calculator.
11.
5+3
9-1

1'. 2
3

4
5+3

1C.
5
2+1
4-1

1&. 4
1
2
- S
2
3

1:.
5+6-

3
-2
2
2
3
-
3
3-6


Addin! and subtractin! vectors and "atrices re)uire both operands to be of the sa"e di"ensions. The
addition and subtraction operation in vectors and "atrices are array operations= they are perfor"ed to
correspondin! ele"ents of the operands. #or exa"ple, define two row vectors first

and then the + 2plus6 si!n will produce the su" of each ele"ent of the vector


Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 24

Gowever, "ultiplication, division and exponentiation in vectors and "atrices are different fro" scalar
operations. These operations follow the rules of "atrix al!ebra, which will be covered in a later topic. There
are correspondin! array operators for these operations= such operators are the sa"e except they are
preceded by a dot> that is .*, ./ and .^ are array "ultiplication, array division and array exponentiation
respectively. A!ain, a re)uire"ent for array operations is that both operands should be of the sa"e
di"ensions. Thus,

are the array products, )uotients and powers of row vectors a and b respectively. These array operations
allow one to do repetitive calculations in MATLAB. #or exa"ple, if you are to convert an!les expressed in
de!rees into radians, you can do all of your conversions usin! a sin!le co""and. Try

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 25


then you can "ae a table of the de!rees0radians values by hori/ontally concatenatin! their transposes so
you could have a table

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 26

E"am#le 1.-
3erfor" the followin! calculations
1. 9efine "atrix a = |
2.S S.8 9
] as a MATLAB variable.
'. #ind the sine of a.
C. Add S to every ele"ent in a.
&. 9efine the "atrix b = |
S.2 S.14 2
] as a MATLAB variable.
:. Add to!ether each ele"ent in "atrix a and in "atrix b.
;. Multiply each ele"ent in a by the correspondin! ele"ents in b.
7. ,)uare each ele"ent in "atrix a.

N%mber di#la! &ormat. By default, MATLAB uses double precision floatin!0point nu"bers in its
calculations, which results in approxi"ately 16 deci"al di!its of precision. 4han!in! the display for"at
does not chan!e the accuracy of the results. When ele"ents of a "atrix are displayed in MATLAB, inte!ers
are always printed without a deci"al point. Gowever, values with deci"al fractions are printed in the default
short for"at that shows four di!its after the deci"al point. Thus,

But

and

MATLAB allows you to specify other for"ats that show additional di!its. The co""and format long
displays results with 1: di!its after the deci"al point. Try
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 27


The co""and format bank displays results in two deci"al places.

Fou can return the for"at to four deci"al di!its with the co""and format short. When nu"bers
beco"e too lar!e or too s"all for MATLAB to display in the default for"at, it auto"atically expresses the"
in scientific notation 2you should have noticed this in the previous exa"ples 1.Ca and 1.Cb6.

Fou can force MATLAB to display all nu"bers in scientific notation with format short e 2with four
deci"al di!its6 or format long e 2with 1S deci"al di!its6. #or instance

Another pair of for"ats that are often useful to en!ineers and scientist is the en!ineerin! notations
format short eng and format long eng. These are in scientific notation but the powers of
ten are in "ultiple of three 2for use with ,I prefixes6. Try
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 28


When a "atrix of values is sent to the screen, and if the ele"ents beco"e very lar!e or s"all, a co""on
scale factor is printed alon! with the scaled values. Try

-ther for"ats that are useful are format + and format rat. The first co""and causes a "atrix to
be displayed as a si!n "atrix= positive values are represented as +, ne!ative values as -, and /ero as
blan. Try

The format rat displays nu"bers as rational nu"bers. Thus,
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 29


The co""ands format short g and format long g selects the best of fixed0point or floatin!0
point representation.

The format loose 2the default6 co""and inserts a line feed between user0supplied expression and
the results returned by the co"puter. The format compact co""and re"oves those line feeds.



Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 30

The table below su""ari/es the available nu"ber display for"ats in MATLAB
Ta'le 1. 2. 3umerical display formats a!aila'le in MATLAB.


Sa.in' !o%r work. MATLAB allows various ways to save your session or your variables in the worspace.
The diary function allows you to record a MATLAB session in a file and retrieve it for later review. To
activate the diary function, type in diary or diary on at the co""and pro"pt. Both the MATLAB
co""ands and the results are stored K includin! your "istaes. To end a recordin! session, type in
diary off at the co""and window.
A file na"ed diary should appear in the current folder. Fou can retrieve the file by double0clicin! on the file
na"e in the current folder window. An editor window will open with the recorded co""ands and results.
Fou can also open the file in any text editor, such as *otepad. ,ubse)uent sessions are added to the end
of the file. If you prefer to store the diary session in a different file, specify the filena"e diary
<file_name> or diary(file_name).
To preserve the variables you created in the co""and window 2which are listed in the worspace
window6, you "ust save the contents of the worspace window to a file. The default for"at is a binary file
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 31

called a "at0file 2*.mat6. To save the worspace, type in save <file_name> or in the ribbon
"enu, clic Sa.e /ork#ace or use the shortcut Ctrl0S. #or the last two "ethods, MATLAB will pro"pt
the user for the file na"e. The MAT0file recently will be saved in the current folder directory.
The "at0file can be loaded into the subse)uent MATLAB sessions by typin! in load <file_name>
at the co""and window, or by double clicin! the file in the current folder window. If the "at0file contains a
variable na"ed as one of the variables existin! in the worspace before loadin!, the previous value of that
variable is overwritten with the value in the "at0file. The save co""and can also choose which
variableAs isAare to be saved in the "at0file, or to an A,4II for"at aside fro" the *.mat for"at the
variables will be saved, for use with other application pro!ra"s or pro!ra""in! lan!ua!es. The !eneral
syntax is save <file_name> <variable_list> -ascii. The file na"e should specify
what extension 2*.dat, *.txt, etc.6 will the file be saved onto> it defaults to *.mat.
4o""ands that you have typed in the co""and window, which are auto"atically saved in the co""and
history, can also be saved in a script file called "0file 2*.m6. The "0files are A,4II text files si"ilar to
4A4LL source code files. It can be created and edited in MATLAB. It is also where MATLAB pro!ra"s are
written.
To save the co""and history in an "0file, ri!ht0clic anywhere in the co""and history window to display
"enu options, then choose Select All 2alternatively, clic anywhere on the co""and history window and
then press Ctrl0A6 then Create Scri#t. Fou can also choose which co""ands are to be saved in an "0file.
The "0file editor appears and you can clic the Sa.e on the ribbon "enu to save the "0file.
The editor also allows you to put co""ents and divide the scripts into cells. 4o""ents can "ade part of
any co""and but are not interpreted or executed as co""ands. +se co""ents sparin!ly to i"prove the
readability and interpretability of your co""ands or codes. A co""ent is identified at the start with a %
sy"bol. 4ells, on the other hand, allow one to divide co""ands or codes and !roup the" accordin!ly. A
cell is "ade with a %% sy"bol at the start of a line.
At this point, always re"e"ber to save your MATLAB sessions in a file for you to review. Also, save all the
variables in a "at0file and the co""ands in an "0file. +se su!!estive na"es for your file na"es so you will
not lose the" 2exa"ple= eion(11+1213 for your diary, eion(11+12134.ariable.mat for the
variables, and so on6.
Drill Problem 1.(
1. Gow can you start MATLABB What are the windows that can be seen in the default MATLAB
environ"ent and how can each one be "anipulated accordin! to one8s preferencesB
'. ?enerate the followin! 2use the default nu"erical display for"at for these6
a. c = 2997294S8, u = 6.67S84 1u
-11
, h = 6.626u69S7 1u
-34
, x = S.S
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 32

b. A =
l
l
l
l
l
4 S 2 S 1
1 u 2 S 1
1u 7 6 S 2
4 S 1 u S
1 4 1 S u
1
1
1
1
1
, B =
l
l
l
l
l
2 S S 4 7
1 4 1 u 1
6 S u 1u S
4 S S 1u 2
2 1 1 1 1
1
1
1
1
1

c. A row vector C which starts fro" 1u, ends with 1u and with ele"ents u.S units apart> a colu"n
vector B that starts fro" u, ends with S and has the sa"e nu"ber of ele"ents as the vector C.
d. E =
l
l
l
l
l
1 1 1 1 1
u 1 1 1 1
u u 1 1 1
u u u 1 1
u u u u 1
1
1
1
1
1
, F =
l
l
l
l
l
1 u u u u
1 1 u u u
1 1 1 u u
1 1 1 1 u
1 1 1 1 1
1
1
1
1
1

e. ,u"s and differences of "atrices A and B, E and F, A and E, B and F.
f. ,u" and difference of C and B expressed as row vectors and colu"n vectors.
!. Array products and )uotients of "atrices A and B, A and E, B and F.
h. Array product of "atrices E and F.
i. Array products and )uotients of x and "atrix A, x and "atrix B.
.. Array product and )uotient of C and B expressed as row vectors and colu"n vectors.
C. In the H'a#rice."lI file, obtain the !as prices data of each of the countries in different colu"n
vectors. *a"e each colu"n vector as the country for which the data belon!s to. Also, create a colu"n
vector of the Year data.
&. Multiply and divide the constant c and the "atrix A. 5xpress the results in different nu"erical for"ats.
9o the sa"e for the products u and B.
:. 5valuate C
2
and B
2
. 5xpress the results in a convenient for"at that displays all the si!nificant fi!ures
of each of the ele"ents.

1.C Built0in functions in MATLAB
At the end of this lesson, the students "ust be able to=
a. use the Gelp feature of MATLAB>
b. use a variety of co""on "athe"atical, tri!ono"etric, statistical and data analysis functions>
c. !enerate rando" nu"bers and "atrices in MATLAB>
d. use functions for co"plex nu"bers>
e. use the special values and functions built into MATLAB.
5in' b%ilt6in &%nction. All functions in MATLAB can be thou!ht of as havin! three co"ponents=
the function na"e>
the re)uired input, called the ar!u"ent>
the output of the function.


Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 33

#or exa"ple, the co""and to tae the s)uare root of an ar!u"ent, sqrt is used as in the followin!
co""and

The co""and has the followin!= a as the ar!u"ent or input of the function, sqrt() is the function na"e,
and the calculated value or output, 6 is assi!ned to the variable b.
In this case, the ar!u"ent of the function sqrt() is a scalar. In !eneral, a function can tae a vector as
an input, in which case, the operation is array0wise, or vectori/ed, as in

or

A function re)uires at least one ar!u"ent, and so"e functions re)uire "ore than one, as in the function

which co"putes the re"ainder when 1u is divided by S.
A function can also return two outputs, such as
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 34


which returns the si/e of the "atrix A. The outputs can be assi!ned to variables in the followin! "anner

There are also functions which do have "ultiple outputs but display only one value when called. #or
exa"ple, the function max() when called returns the value of the ele"ent with the lar!est value in a
!iven vector or "atrix, such that

but it actually returns two values= the "axi"u" value and its position 2or index6 in the vector or "atrix.
Thus,

Indexin! in vectors and "atrices are to be discussed on later topics.
In the later versions of MATLAB, as you type the function, MATLAB displays the re)uired ar!u"ents and
aids you to type in the ar!u"ents in the correct order.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 35

#unctions can be nested, as in

but this can cause "ore confusion than bein! a shortcut so use this with caution.
5in' the help &eat%re. MATLAB offers a variety of "ethods to access its help feature. -ne "ethod is
throu!h the co""and window, as in

To !et help for a particular topic, type in help <topic>. As an exa"ple, let us find out what are the
ele"entary "athe"atical functions in MATLAB=
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 36









Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 37


Fou can also type in a certain function na"e to now how it wors, say

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 38

#unctions with "ultiple inputs and outputs can be seen with this "ethod, as in

which shows that the function re)uires two input ar!u"ents, or

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 39

which shows that so"e of its for"s 2i.e. the second and third for"s6 can have two outputs. The sa"e
docu"entation for functions in MATLAB can be accessed by pressin! 71 or by usin! the Prod%ct $el#.
E"am#le 1.2
+se the Gelp feature of MATLAB to find the function and the correct syntax for the followin! function
na"es.
a. residuez()
b. cart2sph()
c. factorial()
d. poly()
e. reshape()

Elementar! mathematical &%nction. 5le"entary "athe"atical functions include lo!arith"s,
exponentials, absolute value, roundin! functions, and functions used in discrete "athe"atics. The table
below lists the co""on "athe"atical functions. They either accept a scalar or a "atrix of values.
Ta'le 1. . )ommon mathematical functions 1Moore. 2/122

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 40




Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 41

E"am#le 1.8
1. 4reate a vector x fro" 2 to +2 with an incre"ent of 1. #ind the followin!=
a. the absolute value of each of the ele"ents of vector x.
b. the s)uare root of each of the ele"ents of vector x. +se the functions sqrt(), nthroot()
and raise the vector to 12.
'. 4reate a vector y fro" 9 to 12 with an incre"ent of S. #ind the followin!=
a. the )uotient of y and 2. 9isplay the results in rational for". @evert bac to the default for"at after
doin! this part.
b. the re"ainder when y is divided by 2.
c. the vector e
y
.
d. the vector ln y.
e. the vector log
10
y.
C. 9eter"ine the followin!=
a. #actor the nu"ber S22.
b. #ind the !reatest co""on deno"inator of S22 and 6.
c. Is S22 a pri"e nu"berB
d. Gow "any pri"es occur between u and S22.
e. Approxi"ate as a rational nu"ber.
f. #ind 1u!.

5in' tri'onometric &%nction. MATLAB includes a co"plete set of the standard tri!ono"etric and
hyperbolic functions. Most of these functions assu"e that the an!les are expressed in radians. There are
functions however, that expresses an!les in de!rees. The table below shows these tri!ono"etric and
hyperbolic functions.
Ta'le 1. ". Trigonometric and hyper'olic functions 1Moore. 2/122.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 42


E"am#le 1.9
4alculate the followin! usin! MATLAB.
a. sin(2) for = S.
b. cos(0) for u 2> let chan!e in steps of u.2.
c. sin
-1
(1).
d. cos
-1
(x) for 1 x 1> let x chan!e in steps of u.2.
e. cos(4S)> use the two functions appropriate for this purpose.
f. the an!le whose sine is u.S> express your answer both in de!rees and in radians.
!. the cosecant of 6u.

Data anal!i &%nction. The data analysis functions in MATLAB are listed below. It is worth notin! that
MATLAB is colu"n0do"inant> that is, when usin! functions and MATLAB has to choose whether to
evaluate per row or per colu"n, MATLAB would choose to evaluate per row first. #or exa"ple, when you
use the function max() to the "atrix A as

the result is a row vector of the "axi"u" ele"ents of each row. ,ince the function max() can also return
the position of these ele"ents in a row 2usin! its row nu"ber6, it also creates another row vector, as in
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 43


The table below lists the data analysis functions used in MATLAB.
Ta'le 1. %. &ata analysis functions 1Moore. 2/122.


Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 44




Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 45



Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 46




Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 47


E"am#le 1.3
I"port the H'a#rice."lI data into a MATLAB variable called prices and do the followin!=
a. 5dit the variable prices so that the price data for Australia in 1$$( is 0SB 2.4u.
b. 4reate the Year and the prices of !as for each country as variables fro" the prices variable.
c. 9eter"ine the hi!hest and the lowest prices of !as for each of the countries and what year did
these prices prevailed.
d. 9eter"ine which country had the hi!hest and the lowest price for !as for each year.
e. What are the "ean and "edian prices of !as for each country and for each yearB
f. ,ort the prices of !as for each country in ascendin! and descendin! order.
!. 9eter"ine how "any data are available in the variable prices.
h. 9eter"ine the standard deviation and variance of the !as prices for each of the countries and for
each year.

:andom n%mber. @ando" nu"bers are fre)uently used in en!ineerin! and scientific calculations to
si"ulate certain behaviors or pheno"ena. There are two different types of rando" nu"bers that can be
!enerated in MATLAB= unifor" rando" nu"bers and ?aussian or nor"ally distributed rando" nu"bers.
+nifor" rando" nu"bers are evenly distributed nu"bers between u and 1. The table below shows the
co""ands used to !enerate rando" nu"bers.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 48

Ta'le 1. (. Functions that generate uniform random num'ers 1Moore. 2/122.

?aussian rando" nu"bers are nor"ally distributed nu"bers without bound. ?aussian distribution "eans
that data tends to be nearer the "ean and are less liely to occur as we !o farther the "ean. The table
below shows the functions to !enerate ?aussian rando" nu"bers.
Ta'le 1. *. Functions that generate 4aussian random num'ers 1Moore. 2/122.

E"am#le 1.11
9o the followin!=
a. ?enerate a Suu0si/e row vector of unifor" rando" nu"bers.
b. ?enerate a Suu0si/e row vector of unifor" rando" nu"bers between S and 1u.
c. ?enerate a Suu0si/e row vector of ?aussian rando" nu"bers with a "ean of /ero and a variance
of one.
d. ?enerate a Suu0si/e row vector of ?aussian rando" nu"bers with a "ean of S and a standard
deviation of 2.S.
e. 4o"pute the "ean and the standard deviation of the "atrices in the previous parts.

Com#le" n%mber. The co"plex nu"ber a = S + Si = S + jS can be written in MATLAB usin! the
followin! co""ands

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 49


The input to the complex() function can either be a scalar or an array, as in

which then creates a co"plex vector. The real and i"a!inary parts of the co"plex scalar or vector can be
deter"ined usin! the real() or imag() functions, as in

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 50

The con.u!ate of a co"plex nu"ber is found usin! the function conj()

while the transpose operator for co"plex nu"bers returns the co"plex con.u!ate transpose of a vector or
"atrix,

The uncon.u!ated transpose of vector A can be found usin! the . operator, as in

4o"plex nu"bers can be converted into its polar coordinates for", represented by a radius 2distance fro"
the ori!in of the co"plex x0y plane and an an!le fro" the hori/ontal x0plane. The "a!nitude and the an!le
of a co"plex nu"ber can be deter"ined usin! the abs() and the angle() functions respectively.

The table below su""ari/es the functions used for co"plex nu"bers.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 51

Ta'le 1. +. Functions used $ith comple5 num'ers 1Moore. 2/122.


E"am#le 1.11
9o the followin!
1. 4reate the co"plex )uantities
a. a = 1 + i
b. b = 2 Si
c. c = 8 + 2i
d. A co"plex vector B with ui = |
2 4 6
] and ui = |
S 8 16
]
'. #ind the polar coordinates of the vectors in part 216.
C. #ind the con.u!ates of co"plex scalars a, b and c.
&. #ind the transpose and con.u!ate transpose of vector B.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 52

Com#%tational limit o& MATLAB. ,ince co"puters wor on finite resources, there is a li"it on how lar!e
or how s"all a nu"ber can be represented in MATLAB. The followin! functions deter"ine the
co"putational li"its of MATLAB.
Ta'le 1. ,. Functions that determine the computational limits of MATLAB 1Moore. 2/122.

-verflow and underflow occurs when MATLAB co"putations exceed beyond li"its. A calculation lie

results in an overflow since the result 22.Se4uu6 is beyond the lar!est possible floatin!0point nu"ber used
in MATLAB, and the overflow condition is indicated by the Inf result. An Inf result can also be obtained
when dividin! a nu"ber or variable by /ero, as in

An underflow results when the value returned by MATLAB is too s"all to discern with /ero, as in the
co""ands

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 53

In perfor"in! calculations involvin! very lar!e or very s"all nu"bers, it "ay be possible to reorder the
calculation so that MATLAB will not reach overflow or underflow. #or exa"ple, the operation

would overflow since the "ultiplication is perfor"ed fro" left to ri!ht, and the first "ultiplication operation
resulted in an overflow. @earran!in! the operations,

returns an answer which is well within MATLAB8s ran!e.
S#ecial .al%e and micellaneo% &%nction. The table below shows the special values and functions
used in MATLAB.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 54


Drill Problem 1.+
1. 3opulations tend to expand exponentially, that is
P = P
0
e
rt

where
P D current population
P
0
D ori!inal population
i D continuous !rowth rate, expressed as a fraction
t D ti"e
If you ori!inally have 1uu rabbits that breed at a continuous !rowth rate of 9u% 2i.e. i = u.96 per
year, deter"ine the population of the rabbits every six "onths up to ten years 2assu"e that a six0
"onth period is u.S years6.
'. 4he"ical reaction rates are proportional to a rate constant k that chan!es with te"perature accordin!
to the Arrhenius e)uation
k = k
0
e
-
Q
RT

#or a certain reaction, Q = 8uuu calmol, R = 1.987 calmol K, and k
0
= 12uumin. #ind
the values of k for te"peratures T fro" 1uu K to Suu K, with incre"ents of 2u K. 4reate a table of
results.
C. ,o"eti"es it is convenient to have a table of sine, cosine and tan!ent values. 4reate a table of all
three of these tri!ono"etric functions for an!les u to 2, with a spacin! of u.1 radians. Four table
should contain a colu"n for the an!le and then for the sine, cosine, and tan!ent.
&. The displace"ent of the oscillatin! sprin! shown below can be described by x = Acos(ut), and its
acceleration a = Au
2
cos(ut) where x is the displace"ent, a is the acceleration, A is the
"axi"u" possible displace"ent, u is the an!ular fre)uency which depends on the sprin! constant
and the "ass attached to the sprin! and t the ti"e. #ind the displace"ent x and the acceleration a for
ti"es fro" u to 1u seconds, with incre"ents of u.1 seconds if the "axi"u" displace"ent is 4 cm
and the an!ular fre)uency is u.6 iaus. 4reate a table of your answers for ti"e, displace"ent and
acceleration as your colu"ns.

:. 4onsider the followin! table of data representin! te"perature readin!s in a reactor as shown below.
5nter these values in an M, 5xcel file, and save this as thermoco%#le."l. Then i"port these data
into MATLAB as the variable thermocouple and do the followin!=
a. #ind the "axi"u" and the "ini"u" te"perature re!istered for each ther"ocouple.
b. #ind the "ean, "edian and the "ode te"perature of each ther"ocouple.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 55

c. #ind the standard deviation and variance of the te"perature readin!s for each ther"ocouple.

;. It is desired to si"ulate the te"perature readin!s over ti"e of a sensor used to detect heat. 4reate a
?aussian distribution of te"peratures with a "ean of 7uF and a standard deviation of 2F ,
correspondin! to a four0hour duration 2 u min to 24u min6. 4reate a table of values for these
readin!s. Then, deter"ine the followin!=
a. The "axi"u" and the "ini"u" te"perature readin!s.
b. The "ean and the standard deviation of the readin!s.
7. A series @L4 circuit, such as one shown below, consists of the followin! ele"ents and para"eters= A
sinusoidally varyin! volta!e source 2in volts v6, an inductor with inductance L, a capacitor with
capacitance C and a resistor with resistance R. -ne can find the current I flowin! throu!h the circuit by
usin! -h"8s law 2!enerali/ed for alternatin! current 2A46 circuits6 as
v = I Z
T

with Z
T
as the total i"pedance in the circuit. Assu"e the followin!= Z
L
= u + Si, Z
C
= u 1Si
R = Z
R
= S + ui and that Z
T
= Z
C
+ Z
L
+ Z
R
, find the current in the circuit when the volta!e is
v = 1u sin6ut and t is a ti"e vector fro" u to 1u seconds with incre"ents of u.1 seconds.


1.& Manipulatin! "atrices
At the end of this lesson, the student shall be able to=
a. !enerate special "atrices>
b. "anipulate "atrices> and
c. extract and edit ele"ents of "atrices usin! indexin!
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 56

S#ecial matrice. There are "any special "atrices used in "athe"atics and MATLAB has functions
which can !enerate these special "atrices. The previously discussed functions ones() and
zeros()are a"on! these. -ne special "atrix that MATLAB can !enerate is the eye() which
!enerates an identity "atrix, as in

The function repmat() creates a lar!er "atrix by tilin! copies of an input "atrix, as in

-ther speciali/ed "atrices widely used in "athe"atics are the followin!=

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 57


#or exa"ple, the function magic()!enerates the "a!ic s)uare "atrix whose row, colu"n, and dia!onal
su"s are all e)ual, as in

where the first five ele"ents of sumC corresponds to the colu"n su", the next five ele"ents to the row
su", and the last two ele"ents corresponds to the "ain and the secondary dia!onals, of "atrix C.
The pascal()functions !enerate the 3ascal "atrix whose ele"ents are based on the 3ascal8s trian!le,
i.e. the coefficients of the bino"ial expansion (a + b)
n
. #or exa"ple,

It is interestin! to note that the ele"ents of the inverse of the 3ascal8s "atrix are also inte!ers and that the
resultin! "atrix is also sy""etrical, as in
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 58


and that its deter"inant 2or any 3ascal8s "atrix6 is

The 3ascal8s "atrix have wide uses in co"binatorics, a branch of "athe"atics dealin! with the study of
finite discrete structures.
E"am#le 1.1(
+se the Internet to find infor"ation about the Gilbert "atrix 2see 5xa"ple 1.C, ite" nu"ber :6, and
!enerate the Gilbert "atrix in MATLAB.

Mani#%latin' matrice. MATLAB provides various functions to "anipulate "atrices, such are shown
below

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 59

The function cat() contatenates array in the sa"e "anner as the s)uare bracets []. It re)uires
however the di"ension to which the two arrays are to be concatenated. #or exa"ple

The first instance concatenates C and D alon! the first 2row6 di"ension, while the second one
concatenates the" alon! the second 2colu"n6 di"ension. *ote that a!ree"ent between di"ensions is still
re)uired when concatenatin! "atrices this way.
The reshape() function "anipulates "atrices by for"in! an m0by0n "atrix taen fro" colu"nwise
arran!e"ent of the ori!inal "atrix. #or exa"ple,

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 60

reshapes E2 2a S0by01u "atrix6 into a 1u0by0S "atrix F. *ote that the order of ele"ents of "atrix F is
taen as the colu"nwise ele"ents of the ori!inal "atrix E2. Also, the reshape() function re)uires that
the nu"ber of ele"ents of the ori!inal "atrix is "ade intact.
The function diag() has two functions. #irst, it extracts the "ain dia!onal of a s)uare "atrix if its
ar!u"ent is a s)uare "atrix, as in

An additional ar!u"ent to this co""and would !enerate the dia!onal above or below this "ain dia!onal,
as in

It can also !enerate a dia!onal for non0s)uare "atrices. The "ain dia!onal for these "atrices starts with
the first0row, first0colu"n ele"ent and pro!ressin! towards the lower ri!ht of the "atrix until it reaches the
last colu"n, as in
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 61


The additional ar!u"ent for the diag()function are inte!ers that refer to the dia!onals above 2if positive6
or below 2if ne!ative6 to this "ain dia!onal.
,econdly, the diag() function can !enerate a s)uare "atrix whose dia!onal is the ele"ents of the input
vector. #or exa"ple,

This function can also have additional inte!er ar!u"ents, as in
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 62



Trian!ular "atrices are i"portant in the study of linear al!ebra. To extract the", use the functions
tril() and triu(). #or exa"ple,

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 63

*ote that these functions can also have additional inte!er ar!u"ents which can include the dia!onals
above and below the "ain dia!onal. These functions can also wor on non0s)uare "atrices.
The functions fliplr() and flipud() flips the "atrix in left0ri!ht and up0down directions
respectively. #or exa"ple

The function flipdim() flips the "atrix alon! the specified di"ension. #or exa"ple

with which the first expression flips the "atrix D alon! the first 2row6 di"ension while the second expression
flips the sa"e "atrix alon! the second 2colu"n6 di"ension.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 64

E"am#le 1.1+
?iven the "atrices A = magic(5) and B = pascal(5), !enerate the followin! "atrix


Matri" inde"in'. 5le"ents inside "atrices can be extracted usin! indexin!. In MATLAB, there are two
types of indexin!= linear and two0di"ensional indexin!. In linear indexin!, MATLAB assi!ns index to each
of the ele"ents in a linear fashion, startin! with the first0row, first0colu"n ele"ent, !oin! throu!h ele"ents
in the first colu"n, and then starts a!ain on the first0row ele"ent of the second row. #or exa"ple, for the
"atrix

the nu"ber in parenthesis is the ele"ent8s linear index. Fou can recall the ele"ents in MATLAB by typin!
in

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 65

A row or colu"n vector can also be used as a linear index

A ran!e can also be used as a linear index. To extract the second colu"n 2ele"ents 11 thru 2u6,

Third row can be extracted usin! the expression

The eyword end is used to identify the last ele"ent, as in

The row0colu"n indexin! of MATLAB indexes ele"ents in a "atrix usin! an ordered pair of row nu"ber
and colu"n nu"ber. Thus,
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 66


where the nu"bers in the parenthesis is row and colu"n indices of each of the ele"ents. To extract such
ele"ents, type in

An entire row or colu"n can be extracted usin! the colon : operator, as in

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 67

The first expression can be interpreted as Hall rows, third colu"nI of "atrix A. The second expression as
Hthe fourth row, all colu"nsI of "atrix A. The last expression extracts the last row of "atrix A.
A certain ran!e of rows and colu"ns can be extracted fro" "atrices. #or exa"ple,

extracts the second up to the sixth row ele"ents in the last colu"n of "atrix A, or

which extracts the second thru seventh rows of the fourth and fifth colu"ns of "atrix A. *ote that indexin!
is not only used to extract "atrix ele"ents but also to edit the". #or exa"ple, to chan!e the ele"ents of
the entire last row of "atrix A to 1,

E"am#le 1.1,
+sin! the H'a#rice."lI data, do the followin!
a. 4reate the Year vector.
b. 5dit the 1$$( data for Australia to '.$$.
c. 4reate the FraGerMex variable which contains the !as prices in #rance, ?er"any and Mexico.
d. 4reate the "atrix USA which contains the year data on the first colu"n and the !as prices of the
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 68

+nited ,tates on the second colu"n.
e. 4reate the "atrix prices9599 which contains the !as prices for all of the countries.
f. #ind the avera!e prices for each of the country and for each year. 3lace the avera!es on variables
AveCountry and AveYear respectively.
!. #ind out which countries have the hi!hest and the lowest avera!e prices. +se indexin!.
h. #ind out in what year was the avera!e prices hi!hest and lowest. +se indexin!.

Drill Problem 1.,
1. ?enerate the "atrix A as shown below

+se the followin! "atrices= a 1u 1u Gilbert "atrix, an 80ele"ent row vector of 18s, a 2 S "atrix
of u8s, a S S 3ascal "atrix and a S S "a!ic "atrix.
'. I"port the data fro" HElectricit!5e."lI, excludin! the date colu"n and other text data. Then do the
followin!=
a. +sin! indexin!, extract the data for the residential, co""ercial and industrial colu"ns, callin!
these variables as residential, commercial and industrial respectively.
b. Tae note that each colu"n vector !enerated in part 2a6 is arran!ed on a "onthly basis. @eshape
the data so that the data is arran!ed per year on a row basis, and "onthly on a colu"n basis.
c. 9eter"ine the "onthly su"s of electricity use per sector 2residential, co""ercial and industrial6.
-n the avera!e, which three "onths are the hi!hest for all the sectorsB Which three are the
lowestB
d. 9eter"ine the yearly totals of electricity consu"ption per sector. -n the avera!e, which three
years are the hi!hest for all the sectorsB Which three are the lowestB
e. 4reate the TotalElecUse variable. The variable consists of three rows representin! the
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 69

residential, co""ercial and industrial electricity use for each year fro" 1$$1 up to '(($. #ro"
this, deter"ine the yearly totals of electricity consu"ption.

1.: 3lottin!
At the end of this lesson, the student shall be able to=
a. create, edit and annotate two0 and three0di"ensional plots of various data in MATLAB> and
b. use MATLAB8s interactive plottin! tools.
?raphs are used by scientists and en!ineers to visually interpret their lar!e set of data. MATLAB contains
powerful !raphics and visuali/ation capabilities which can be used to translate arrays and "atrices into
!raphs.
Two6dimenional #lot. Two0di"ensional !raphs plots x0 y pairs into a two0di"ensional coordinate
syste", hence, plottin! re)uires two vectors= one for the dependent variable, and the other for the
independent variable. Thus,

A window with the default title 7i'%re 1 will pop up and show the plot of the variable x a!ainst y.

Figure 1. 1". 6lot of 5 against y.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 70

The plot above can be annotated with the followin! co""ands

and the !raph would loo lie

Figure 1. 1%. Annotated plot.
We will learn other techni)ues of annotatin! plots later.
Alternatively, selectin! the variables in the worspace and then ri!ht0clicin! on the selected variables will
show an option to plot the variables.
In so"e cases, one will need to plot "ultiple sets of data. This can be acco"plished by usin! "ultiple
fi!ures, "ultiple axes in a fi!ure, or "ultiple plots in a set of axes.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 71


Figure 1. 1(. 4raphics structure in MATLAB.
A fi!ure window in MATLAB can be su""oned by typin! in the figure co""and. It "ay or "ay not
have an inte!er ar!u"ent> if it does, the fi!ure that appears is assi!ned with that inte!er ar!u"ent> if it
does not have an ar!u"ent, MATLAB assi!ns the latest available inte!er based on those already opened.
MATLAB plots on the currently open fi!ure window.


Figure 1. 1*. #sing multiple figures.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 72

Within a fi!ure window, one can create several plots on different set of axes usin! the subplot
co""and. This co""and will create m n axes on a fi!ure window. Thus to plot the followin! data

use the followin! co""ands

which will open the fi!ure window as seen below

Figure 1. 1+. Figure $indo$ $ith su'plots.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 73

The ar!u"ents for the function subplot()consist of an ordered triple, which denotes the nu"ber of
rows, the nu"ber of colu"ns of the plots, and the inte!er assi!n"ent for each plot. It can be written as
subplot(mnp)or subplot(m,n,p)where m is the nu"ber of rows, n the nu"ber of colu"ns of
the arrays of plot and p is the inte!er assi!n"ent of the position of the plot, counted row0wise startin! fro"
the first row K first colu"n plot and !oin! fro" left to ri!ht.
Asy""etric subplots can be drawn in a fi!ure by usin! a vector as a positional value. #or exa"ple, the
co""ands

creates the followin! fi!ure

Figure 1. 1,. Asymmetric su'plot.
while the co""ands

displays the followin!
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 74


Figure 1. 2/. Asymmetric plots.
Multiple plots inside a set of axes can be done by expressin! the data to be plotted in a "atrix. #or
exa"ple, the data in the H'a#rice."lI fro" second thru eleventh colu"ns can be plotted a!ainst the
years in the first colu"n can be plotted usin! the co""and

and the followin! fi!ure will appear

Figure 1. 21 Multiple plots in a set of a5es.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 75

The hold or hold on co""and can also be used to i"pose a plot unto a set of axes. The co""ands

will plot the second colu"n of the gasprices data a!ainst the first colu"n. We can i"pose the data on
the third colu"n by usin! the followin! co""ands

which results in the followin! fi!ure

Figure 1. 22. 0mposing plots on a set of a5es.
*ote that the hold co""and by itself is released when another hold co""and or the co""and hold
off is issued. To per"anently hold the plots, use hold on co""and. Another "ethod to plot "ultiple
data in a set of axes is by ordered x0y pairs as in

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 76


Figure 1. 2. 6lotting using ordered 57y pairs.
Line #ro#ertie. +sin! the co""and window, the line properties of the plots can be altered. The line type,
"ar and color can be specified by a co"bination of strin!s based on the table below.
Ta'le 1. 1/. Line. mark and color options.

#or exa"ple, the co""ands
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 77


will produce the plot below

Figure 1. 2". Line. mark and color options.
-ther line properties and specifications can be edited thru MATLAB8s interactive tool which will be
discussed later.
A"i calin' and annotatin' #lot. MATLAB auto"atically !enerates the x0 and y0axes scalin! for the
plots, but usin! the function axis the user can control the axis scalin!. #or exa"ple, the co""ands

plots y1, y2 and y3 on one set of axes as seen in fi!ure 1.':. *ote that the axis co""and set the
li"its of the x0 and y0axes fro" u to S and fro" S to S respectively.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 78


Figure 1. 2%. 6lot $ith a5is control.
The function axis also accepts strin! inputs such as tight, as in the followin!


Figure 1. 2(. 6lot $ith tight a5is.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 79

MATLAB provides different annotation techni)ues. The functions xlabel, ylabel, and title which
were used in previous discussions are part of those techni)ues. -ther annotation techni)ues include the
function legend which labels each plot in the axes, as in


Figure 1. 2*. 6lot $ith annotation.
-ther annotation "ethods can be done with MATLAB8s interactive plot tool.
Interacti.e #lot tool. MATLAB has an interactive plottin! tool which can be used to plot, create and edit
plots. It can be accessed by the co""and plottools or by openin! a fi!ure and then clicin! the plot
tools icon as shown in fi!ure 1.'%.

Figure 1. 2+. 6lotting tools icon in a figure $indo$.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 80

The plottin! tool window contains six panes by default=
new subplots,
variables,
annotations,
plot browser,
property editor, and
the fi!ure window.
-ne can start by selectin! the variables to be plotted into the fi!ure window.

Figure 1. 2,. 6lotting t !ersus y1.
The fi!ure window can be edited by selectin! the fi!ure window and the options for editin! the window
appears at the botto" pane. We can chan!e the 7i'%re color to /hite and the title to HPlot o& .ario%
&%nctionI. Turn the Show 7i'%re N%mber off by unchecin! the option. The fi!ure window will loo lie
the one shown in fi!ure 1.C(

Figure 1. /. 8diting the figure $indo$ using the plot tool.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 81

More properties of the fi!ure window can be edited by clicin! the More Pro#ertie button of the Pro#ert!
Editor ; 7i'%re pane.
The axes can be edited by selectin! the axes, and the options for editin! the axes appear at the botto"
pane. #or exa"ple, we can put title to this plot by typin! in HLinear &%nctionI in the Title field of the
Pro#ert! Editor 6 A"e. We can chan!e the axes Color to yellow, and the Te"t and line color o& <) =
and > a"e to blue. 4hec the E and F ?rid option to turn the !rid on. The x0axis can be labeled as H"6
a"iI by typin! in the strin! in the < label field under the < a"i tab. 4lic the = a"i tab and type in H!6
a"iI in the = label field. The Tick option allow us to specify the labelin! of tics for the x0, y0 or z0axes.
There is also an option for chan!in! the li"its of the axis, as well as the scalin!. 5dit the axes accordin!ly
so that the new fi!ure is as shown in fi!ure 1.C1.

Figure 1. 1. 8diting the a5es properties.
*ew subplots can be inserted by selectin! the layout of the subplots under the New S%b#lot pane. ,elect
the 20by02 layout, delete the upper ri!ht layout and then resi/e the upper left layout so that the layout in
fi!ure 1.C' is as shown.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 82


Figure 1. 2. Adding and resi-ing su'plots.
Fou can add line ob.ects into the subplots by selectin! the variables under the *ariable pane to be plotted
and either by ri!ht0clicin! onto these variables and then choosin! the ri!ht plot for"at, or by dra!!in! the
variables inside the subplots. Fou can also use the Add Data button under the Plot Brower pane and
then selectin! the x0axis and y0axis data sources. 9oin! additional editin! tass, your fi!ure "ust now loo
lie the one shown in fi!ure 1.C'.

Figure 1. . 8diting a5es.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 83

Fou can edit line series properties in the plot tool by selectin! the plot ob.ect to be edited and the Pro#ert!
Editor ; Lineerie appears at the botto" pane. Fou can chan!e the Plot t!#e, Line Pro#ertie 2type,
width and color6 as well as the Marker Pro#ertie 2type, width, fill color and outline color6. More properties
beco"e available for editin! when the More Pro#ertie button is cliced. The plots can be edited as shown
in the fi!ure below.

Figure 1. ". 8diting plot o'9ects.
Additional annotation tools are provided under the Annotation pane on the left side of the fi!ure window.
Gere, you can use drawin! ob.ects to annotate the plotAs.
Other two6dimenional #lot. -ther two0di"ensional plots are available in MATLAB.
The polar plot is a plot of two variables in polar coordinates. #or exa"ple,

produces the polar plot of fi!ure 1.C:. *otice in the title annotation that the ?ree letter was used.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 84


Figure 1. %. 6olar plot
Lo!arith"ic plots are useful when plottin! exponentially varyin! plots. The table below shows the available
functions to !enerate lo!arith"ic plots.
Ta'le 1. 11. Ta'le of rectangular and logarithmic plotting functions.

#or exa"ple,

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 85


The plot function plots the variable y usin! linear x0 and y0 axes. The function semilogx plots y
versus log x, the function semilogy plots log y a!ainst linear x and finally, the function loglog
plots log y versus log x. The output is shown below.

Figure 1. (. :ectangular and logarithmic plots.
Bar !raphs, pie charts and histo!ra"s are popular !raph for"ats for presentation. Table 1.1' su""ari/es
the functions for !eneratin! these types of plots.
Ta'le 1. 12. Functions for generating 'ar graphs. pie charts and histograms.

An exa"ple for !eneratin! these types of !raphs is de"onstrated below.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 86



Figure 1. *. Bar and pie charts.
Gisto!ra"s are useful for statistical analysis of distributions. It divides the interval of "ini"u" and
"axi"u" into ten bins 2cate!ories6 by default. #or exa"ple,


Figure 1. +. ;istogram.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 87

The histo!ra" is useful for showin! rando" nu"ber distribution, as in


Figure 1. ,. ;istogram for 4aussian and e!enly distri'uted random num'ers.
By default, the histo!ra" divides the data into ten bins, but it can be specified, as in


Figure 1. "/. ;istogram $ith 2% 'ins.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 88

3lottin! two sets of data with !reat difference in "a!nitude on one set of axes can "ae the s"aller data
insi!nificant co"pared to the lar!er one. #or exa"ple,


Figure 1. "1. 6lot $ith single y7a5is scaling.
Gere, it is difficult to see the sine plot since it is way "uch s"aller than the exponential plot. #or this, it is
possible that the two plots will use different y0axis scale by usin! the plotyy function, as in

#i!ure 1.&' shows the output of such co""ands. The plotyy function also taes in ar!u"ents to
chan!e the scalin! of x0 andAor y0axis scalin! fro" linear to lo!arith"ic.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 89


Figure 1. "2. :egular plot !ersus plot $ith y7a5is scaling.

-ne can also plot functions into MATLAB without definin! a vector to which the function is to be plotted.
The co""and

plots the function specified by the strin! sin(x) for the interval 2 up to 2. #i!ure 1.&C shows the
output.

Figure 1. ". Function plot.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 90

The whole list of MATLAB8s two0di"ensional plottin! functions is shown below. This table can also be seen
on MATLAB8s docu"entation at MATLAB @@ ?ra#hic @@ (6D and +6D Plot @@ Plottin' Baic.
Ta'le 1. 1. MATLAB 27& plotting functions.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 91

Three6dimenional #lottin'. MATLAB also provides functions for plottin! in three0di"ensions. The
function plot3 is si"ilar to the plot function, except that it accepts data in three di"ensions, that is, it
re)uires three vectors. #or exa"ple

These co""ands create an ordered triple which defines a spiral plot. The coordinate axes are oriented
accordin! to the ri!ht0hand rule. The above co""ands produce the followin! fi!ure window.

Figure 1. "". Three7dimensional plot using plot.
The mesh function draws a wirefra"e "esh with color proportional to the value of z. It can plot a two0
di"ensional m n "atrix, with the x0 and the y0axis auto"atically assi!ned with the vectors x = 1:n
and y = 1:m. The followin! exa"ple de"onstrate this

The mesh function will create an ordered triple of (i, j, z
j,I
) where i is the colu"n nu"ber and j is the row
nu"ber of the ele"ent z
j,I
. #or exa"ple, the data tip in fi!ure 1.&: points to the third row 2y D S6, third
colu"n 2x D S6 ele"ent of the vector z, which is e)ual to S. MATLAB will then connect these points to
create a wirefra"e "esh.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 92


Figure 1. "%. Mesh plot of the !ector -.
The mesh function also allows three vectors as an ar!u"ent, as in


Figure 1. "(. Mesh plot $ith specified 5 and y !ectors.
*ote that the difference between fi!ures 1.&: and 1.&; is the x0 and y0 axes.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 93

3lottin! "esh plots for functions re)uire that you co"pute the output of the function for co"binations of the
two variables. #or exa"ple, if you have the function f(x, y) = x
2
+ y
2
!iven vectors x = |
1 2 S
]
and y = |
4 S 6
], you need to co"pute f(x, y) for the followin! pairs of x and y= (1, 4), (1, S),
(1, 6) , (2, 4) , (2, S) and so on. In MATLAB, to establish those co"binations, we can use the
meshgrid function, as in

With this, one now can co"pute the values of f(x, y) for every co"bination of the ele"ents of vectors x
and y,

that is, the value of f(1,4) = 4.12S1, f(1,S) = S.u99u, f(1,6) = 6.u828 and so on. We use this
principle to !enerate "esh plots for functions lie f(x, y) = sinc (x
2
+ y
2
) = sin
[x
2
+y
2

x
2
+y
2
. Thus,

which first !enerates two0di"ensional "atrices X and Y and then co"putes R and subse)uently Z. The
plot of the function is shown in fi!ure 1.&7. *ote that the plot is truncated at the top, which is due to the
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 94

round0off error produced when MATLAB tries to evaluate Z when both x and y are /ero. This can be
corrected by addin! the nu"ber eps to R so that the )uantity uu is avoided when co"putin! Z.

Figure 1. "*. Mesh plot for function sinc 1<2.
The surf function is used in the sa"e "anner as that of the mesh function, except that it !enerates a
colored surface, rather than a wirefra"e "esh.


Figure 1. "+. =urface plots for !ectors.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 95



Figure 1. ",. =urface plot for sinc1<2.
4ontour plots are two0di"ensional representation of three0di"ensional data. 4ontour lines are curves alon!
which a function has a constant value. The colors represent the differences in hei!ht 2values of z6.

Figure 1. %/. 4enerating contour lines. 0mage retrie!ed from Wikipedia
1http>??en.$ikipedia.org?$iki?File>)our'e@ni!eau.s!g2
The followin! co""ands !enerate the contour and surface with contour plots of the function peaks in
MATLAB.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 96



Figure 1. %1. )ontour and surface $ith contour plots.
The color sche"es in the fi!ure window can be altered usin! the colormap function. #or exa"ple the
co""and

chan!es the color sche"e of fi!ure 1.:1 into !rayscale, as in

Figure 1. %2. )ontour and surface plots using the grayscale color scheme.
Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 97

Type in help colormap for other options for the color sche"e.
Table 1.1& lists all the available three0di"ensional plottin! functions in MATLAB.
Ta'le 1. 1". Three7dimenional plotting tools.



Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 98

Drill Problem 1.-
1. ?iven the followin! set of functions fro" x = u to 1u,
2a6 y
a
= e
x
, an exponential function
2b6 y
b
= sin(x), a sinusoidal function
2c6 y
c
= Sx
2
+ 2x + 4, a )uadratic function
2d6 y
d
= Vx, a root function
choose appropriate spacin! for the data to ensure s"ooth plot and do the followin! usin! the co""and
window=
a. 3lot each of the functions in separate fi!ure windows, puttin! titles, x0 and y0axis labels, !rids and
le!ends into each.
b. 3lot each of the functions in one fi!ure window, but in separate set of axes, puttin! titles, x0 and y0
axis labels, !rids and le!ends into each.
c. 3lot all of the functions in a sin!le set of axes, puttin! x0 and y0axis labels, !rid and le!ends to
each line ob.ect. 4han!e the line property of each to the followin!= y
a
= solid and blue> y
b
= dashed
and blac> y
c
= dotted and cyan> y
d
= dashed0dotted and "a!enta.
d. 3lot y
a
and y
d
on a sin!le set of axis with two differently and lo!arith"ically scaled y0axis, puttin!
x0 and y0axis labels, !rid and le!ends to each line ob.ect.
e. 3lot y
a
, y
c
and y
d
on one subplot with linear x0 and y0axis, and on another subplot with
lo!arith"ic x0 and y0axis, puttin! correct x0 and y0axis labels on each axes, !rid and le!ends to
each line ob.ect. 4han!e the line property of each to the followin!= y
a
= dotted, !reen and star
"arer> y
c
= dashed, blac and circle "arers> y
d
= dashed and dotted, "a!enta and dia"ond
"arers.
'. 3roduce the followin! plots for the indicated set of data=
a. The polar plots for the n0leaf roses i = a + bcos(k) where a = b = k = 1, a = b = k = 2,
and so on until a = b = k = S . +se u 2 with appropriate spacin!. +se different set of
polar axes for each, with proper annotation for better understandin! the plots.
b. #or scores of the students in a "ath exa" which are represented in the vector
u = |68 8S 61 7u 7S 82 S7 6S 76 8S 62 71 96 78 76 68 72 7S 8S 9S], sort the
data usin! MATLAB and then create a hori/ontal 2on one set of axes6 and a vertical 2on another
set of axes6 bar !raph for u on one fi!ure window.
c. #or the vector u in 2b6, create a histo!ra" in one subplot which divides the scores into five bins
2cate!ories6. The hi!hest cate!ory represents a !rade of A, the next hi!hest, B, and so on until the
lowest cate!ory havin! a !rade of 5. In another subplot under the histo!ra", create a pie chart for
this distribution. Annotate each of the plots properly.
C. 4reate x and y vectors fro" S to S with a spacin! of u.S. +se meshgrid function to "ap x and
y onto two new two0di"ensional "atrices called X and Y. +se your new "atrices to calculate vector
Z = ln VX
2
+ Y
2
. Then do, the followin!, usin! different fi!ure windows for each ite".
a. +se the mesh plottin! function to plot Z. 4o"pare the plots when usin! only one ar!u"ent for
mesh and when usin! three ar!u"ents.
b. +se the contour function to plot Z. 3lace a colorbar onto the plot for you to be able to interpret
the contour plot.
c. +se the surf and surfc plottin! functions to plot Z. 4o""ent on the differences. 4han!e the
color"ap to H#rimI.

Fundamentals of MATLAB Programming

Basic MATLAB Concepts Page 99

:E7E:ENCESA
Moore, G. 2'(1'6. MATLAB for engineers (3rd ed.). *ew 1ersey, +nited ,tates= 3earson

MathWors, Inc. 2'(1C6. MATLAB Documentation. The MathWors, Inc.= +nited ,tates.

You might also like