You are on page 1of 64

Lecture:Fundamentalsof

Matlab
GregorioM.VlezGarca
ChE 4134ChemicalProcessModeling
Spring2012:Jan.23,2012
Referencematerial
Chapra,S.C&Canale,R.P.NumericalMethodsforEngineers",5
th
.Chapter2.
Chapra,S.C.AppliedNumericalMethodswithMATLABforEngineeringand
Science,Chapter2.
Zhang,J.(2009).ComputerApplicationsinEngineeringandConstruction:CVEN302
[Lecturenotes].Texas,USA:TexasA&M,DepartmentofCoastal&Ocean
Engineering.
Lapuerta,V.andLaveron,A.NumericalAerodynamics:OCW.[Lecturenotes].
Madrid,Spain:Polythechnic UniversityofMadrid,DepartmentofAerospace
engineering.
EngineeringFundamentals:EngineeringH192[Lecturenotes].Ohio,USA:Ohio
StateUniversity,CollegeofEngineering.
Ozgu,O.MatlabBasics:AlgorithmandprogrammingI,[Lecturenotes].,Turkey:
Bilkent University,ComputerScience.
Agenda
WhatisandWhyweuseMATLAB
Programdocumentation
DescriptionofMATLABWindows
Generalfunctions,operatorsandvaluestomanage
MATLABEnvironment
Scalars,Vectors,MatricesandArrays
Basics
Mathematicaloperationsandtheirpriorities
Arrayoperations
Builtinfunctions
Inputoutput
What is and why we use
Matlab
MATLAB
MatrixLaboratory
MATLAB is anumerical computing environment andprogramming language
(initially written inC).MATLABallows easy matrix manipulation,plotting of
functions anddata,implementation ofalgorithms,creation ofuser interfaces,
andinterfacing with programs inother languages.
MATLABmakes mathematical operations with vectorsymatrices.Asa
particularcase,itcanalsoworkwithscalarnumbers,bothrealsand
complexes.
It haspackages with specialized functions.
WhyMATLAB?
Industrystandardsoftwareapplication
Wealthofbuiltinfunctionsandlibraries
Toolboxes (addonsoftwaremodules) image
andsignalprocessing,controlsystemsdesign,
fuzzylogic,etc.
Hasownstructuredprogramminglanguage
Easeofapplicationandtesting(pre andpost
processingwithoutlotsofprogrammingand
formatting)
Platformindependent
MATLAB
MATLABisanumericalanalysissystem
Canwriteprograms,buttheyarenot
formallycompiled
Shouldstillusestructuredprogramming
Shouldstillusecomments
Commentsareindicatedby%atthe
beginningoftheline
ProgramDocumentation
Comments!!!
ProgramDocumentation
Youmustincludecommentsinthe
computerprogramsyouturnin
otherwisewewillhavegreatdifficulty
knowingwhatyouaredoing
Forexample,hereissomecrypticcode
withoutcomment
for j=0:2
k=(2-j)*(1+3*j)/2
end
Whatdoesitdo?
Putacommentin
% turns (0,1,2) into (1,2,0)
DescriptionofMATLABWindows
MATLABWindows
CommandWindow
entercommandsanddata
printresults
EditWindow(Editor)
createandmodifymfiles
Currentfolder
indicatefilesincurrent
folder
Workspace
indicateanddescribethe
variablesinmemory
Commandhistory
showcommandstyped
GraphicsWindow
displayplotsandgraphs
DetailsWindow(2010ver)
Provideapreviewofthefile
Allownavigatethecellsin
anmfile
Putwindowsandshowallelements
Editor
Workspace
CommandHistory
CommandWindow
CurrentFolder
Detailswindow
(newfeature)
ResourcesofinMatlab
Generalfunctions,operatorsandvalues
tomanageMATLABEnvironment
ManagingMATLABEnvironment
whoorwhos Seethecurrentruntime
environment
clear removeallvariablesfrommemory
clc clearthecommandwindow
clf clearthegraphicswindow
save savetheworkspaceenvironment
load restoreworkspacefromadiskfile
abort CTRLC
help helpcommand
Really good help command
MATLABSyntax
Nocomplicatedrules
Perhapsthemostimportantthingto
rememberissemicolons (;) attheendof
alinetosuppress output
Typemore ontokeeptextfrom
leavingscreentoofast
diary filename savesatextrecordof
session
diary off turnsitoff
Datatypes
Allnumbersaredoubleprecision(real
numbers)
Textisstoredasarraysofcharacters
Youdonthavetodeclarethetype of
data(definedwhenrunning)
MATLABiscasesensitive!!!
VariableNames
Usually,thenameisidentifiedwiththeproblem
Variablenamesmayconsistofupto31 65
charactersin2011version
Variablenamesmaybealphabetic,digits,andthe
underscorecharacter(_)
Variablenamesmuststartwithaletter
ABC,A1,C56,CVEN_302
day,year,iteration,max
time,velocity,distance,area,density,pressure
Time,TIME,time(casesensitive!!)
InitializingVariables
Explicitlylistthevalues
readsfromadatafile
usesthecolon(:) operator
readsfromthekeyboard
A = [1; 3; 5; 10]; B = [1 3 5; -6 4 -1]
C = [2 3 5 1; 0 1 (continuation)
1 -2; 3 5 1 -3]
E = [A; 1; A]; F = [C(2,3); A]
Specialvalues
pi:t valueupto15significantdigits
i,j:sqrt(1)
Inf:infinity(suchasdivisionby0)
NaN:NotaNumber(divisionofzerobyzero)
clock:currentdateandtimeintheformof a6element
rowvector containingtheyear,month,day,hour,
minute,andsecond
date:currentdateasastringsuchas16Feb2004
eps:epsilon isthesmallestdifferencebetweentwo
numbers
ans:storestheresultofanexpression
Formatofnumbers
Changingthedataformat
>>value=12.345678901234567;
format short 12.3457
format long 12.34567890123457
format shorte 1.2346e+001
format longe 1.234567890123457e+001
format shortg 12.346
format longg 12.3456789012346
format rat 1000/81
Lect18 P.23 WinterQuarter
MATLABRelationalOperators
MATLABsupportssixrelationaloperators.
LessThan <
LessThanorEqual <=
GreaterThan >
GreaterThanorEqual >=
EqualTo ==
NotEqualTo ~=
RelationalOperators
a=1,b=2,x=1,y=b
a*b>0_____
b==2_____
x>7_____
y>d_____
Lect18 P.25 WinterQuarter
MATLABLogicalOperators
MATLABsupportsthreelogicaloperators.
not ~ %highestprecedence
and & %equalprecedencewithor
or | %equalprecedencewithand
Tableoftruth
x Y ~ (x) x& y x| y
True True False True True
True False False False True
False True True False True
False False True False False
Practice
a=1,b=2,x=1,y=b
a*b>0&b==2&x>7|~(y>d)
a*b>0& b==2& x>7| ~(y>d)
1*2>0& 2==2& 1>7| ~(b>d)
2>0& 2==2& 1>7| ~(b>d)
False& True& False| ~(False)
False& True& False| True
False& False| True
False| True
True
Lect18 P.28 WinterQuarter
MATLABLogicalFunctions
MATLABalsosupportssomelogicalfunctions.
xor (exclusiveor)Ex:xor (a,b)
Whereaandbarelogicalexpressions.Thexor operator
evaluatestotrueifandonlyif oneexpressionistrueand
theotherisfalse.Trueisreturnedas1,falseas0.
any(x) returns1ifanyelementofxisnonzero
all(x) returns1ifallelementsofxarenonzero
isnan (x) returns1ateachNaN inx
isinf (x) returns1ateachinfinityinx
finite(x) returns1ateachfinitevalueinx
Scalars,Vectors,Matricesand
Arrays
Basics
MATLAB
MATLABsbasiccomponentisaVector orMatrix
Evensinglevaluevariables(Scalars)
Alloperationsareoptimizedforvectoruse
LoopsrunslowerinMATLABthaninFortran(nota
vectoroperation)
size commandgivessizeofthematrix
Scalars,Vectors,MatricesandArrays
MATLABtreatvariablesasmatrices
Matrix (m n) asetofnumbersarrangedinrows(m)and
columns(n)
Scalar:1 1matrix
RowVector:1 nmatrix
ColumnVector:m 1matrix
| | | |
(
(
(




=
(
(
(

= =
= =
2 2 7 1 5 0
5 9 2 3 4 2
5 2 3 1

21 7
3 2
02 5
21 7 3 2 02 5 27 5
. .
. . D
.
.
.
' B C
. . . B . A
>> pi
ans =
3.1416
>> size(pi)
ans =
1 1
>> a=[1 2 3; 4 5 6]
a =
1 2 3
4 5 6
>> size(a)
ans =
2 3
a=
1416 3. pi =
(

=
6 5 4
3 2 1
a
Arrays
Basicorganizationalformforvariables
Itisusedtostorevaluesofalltypesof
variables.
Scalars,vectors,matrices,cellarrays,structures,
andobjects
Scalars,vectors,andmatricesarenumericor
logicalarrays
Complexvariables
MATLABhandlescomplexarithmeticautomatically
Noneedtocomputerealandimaginaryparts
separately
Theunitimaginarynumberi =ispreassigned 1
x=5+2*i
x =
5.0000 + 2.0000i
y=5*x+3
y =
28.0000 +10.0000i
x=3+5-0.2
x =
7.8000
y=3*x^2+5
y =
187.5200
z=x*sqrt(y)
z =
106.8116
A=[1 2 3; 4 5 6]
A =
1 2 3
4 5 6
b=[3;2;5]
b =
3
2
5
C=A*b
C =
22
52
who
Your variables are:
A b y
C x z
whos
Name Size Bytes Class
A 2x3 48 double array
C 2x1 16 double array
b 3x1 24 double array
x 1x1 8 double array
y 1x1 8 double array
z 1x1 8 double array
save
Saving to: matlab.mat
save matrix1
MATLABExample
default filename
filename matrix1
MatrixConcatenation
4 9 7 y ; 3 2 1 x = =
4 9 7 3 2 1 y x z = =
3 2 1 4 9 7
4 9 7 3 2 1 x y ; y x v = =
4 9 7
3 2 1 y ; x u = =
(
(
(
(

=
(
(
(
(

=
4 1
1 2
1 0
5 2
F
4 1 0
1 2 3
1 0 1
5 2 1
C
ColonOperator
Creatingnewmatricesfromanexistingmatrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]
(

=
(
(
(
(

=
1 2 3
1 0 1
E
4 1 0
1 2 3
1 0 1
5 2 1
C
ColonOperator
Creatingnewmatricesfromanexistingmatrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
E = C(2:3,:) = [-1 0 1; 3 2 -1]
ColonOperator
Creatingnewmatricesfromanexistingmatrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
G = C(3:4,1:2) = [3,2; 0,1]
(

=
(
(
(
(

=
1 0
2 3
G
4 1 0
1 2 3
1 0 1
5 2 1
C
ColonOperator
Variable_name=a:step:b
time=0.0:0.5:2.5
time=[0.0,0.5,1.0,1.5,2.0,2.5]
Negativeincrement
values=10:1:2
values=[10,9,8,7,6,5,4,3,2]
linspaceFunction
linspace(x1,x2) gives100evenlyspaced
valuesbetweenx1andx2
x=linspace(x1,x2)
linspace(a,b,n) generatenequallyspaced
pointsbetweenaandb
x=linspace(a,b,n)
linspace(0,2,11)
ans =
Columns 1 through 7
0 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000
Columns 8 through 11
1.4000 1.6000 1.8000 2.0000
logspaceFunction
logspace(a,b,n)generatesalogarithmically
equallyspacedrowvector
x=logspace(a,b,n)
logspace(a,b)generates50logarithmically
equallyspacedpoints
x=logspace(a,b)
logspace(-4,2,7)
ans =
0.0001 0.0010 0.0100 0.1000 1.0000 10.0000 100.0000
SpecialMatrices
(

=
(
(
(

=
(
(
(

=
(
(
(

=
1 1 1 1
1 1 1 1
ones(2,4)
1 1 1
1 1 1
1 1 1
) 3 ( ones
0 0
0 0
0 0
zeros(3,2)
1 0 0
0 1 0
0 0 1
) 3 ( eye
Scalars,Vectors,Matricesand
Arrays
Mathematicaloperationsandtheir
priorities
b a b a b a
b a
a
b
b a
b a b a b a ab
a a
b a a
b
+ +
=


; n subtractio and Addition
\ \ division Left \
/ ; * ; division and tion Multiplica / *
Negation
^ tion Exponentia ^
Form MATLAB Operation Symbol
ScalarArithmeticOperations
Example: x = (a + b*c)/d^2
count = count + 1
(Matrix inverse)
In order of priority
OrderofPrecedenceofArithmetic
Operations
1. Parentheses, starting with the innermost pair
2. Exponentiation, from left to right
3. Multiplication and division with equal precedence, from left
to right
4. Addition and subtraction with equal precedence, from left
to right
Examples: factor = 1 + b/v + c/v^2
slope = (y2 - y1)/(x2 - x1)
loss = f * length/dia * (1/2 * rho * v^2)
func = 1 + 0.5*(3*x^4 + (x + 2/x)^2)
OrderofPrecedenceofArithmetic
Operations
The priority order can be overridden with parentheses
y = -7.3^2
y =
-53.2900
y=(-7.3)^2
y =
53.2900
a=3; b=5; c=2;
s1 = a-b*c
s1 =
-7
s2=(a-b)*c
s2 =
-4
Exponentiation has higher
priority than negation
Multiplication has higher
priority than subtraction
Scalars,Vectors,Matricesand
Arrays
Arrayoperations
ArrayOperations
Anarrayoperationisperformed
elementbyelement
B(5); * A(5) C(5)
B(4); * A(4) C(4)
B(3); * A(3) C(3)
B(2); * A(2) C(2)
B(1); * A(1) C(1)
=
=
=
=
=
MATLAB: C = A.*B;
] , [ ] ^ , ^ [ ] , [ ].^ , [
] , [ ] ^ , ^ [ ] , [ .^
] , [ ] ^ , ^ [ ].^ , [ .^ tion exponentia Array .^
] . , . [ ] \ , \ [ ] , [ \ ]. , [ division left Array \ .
] . , . [ ] / , / [ ] , /[ ]. , [ division right Array ./
] , [ ] , [ * ]. , [ tion multiplica Array * .
] , [ ] , [ ] , [ n subtractio Array -
] , [ ] , [ ] , [ addition Array
] , [ ] , [ n subtractio array - Scalar -
] , [ ] , [ addition array - Scalar
Example Form Operation Symbol
81 25 4 3 2 5 4 2 3 5
243 9 5 3 2 3 5 2 3
8 64 3 2 3 4 3 2 4 B A
7143 0 667 2 5 7 8 3 5 8 7 3 A.\B
400 1 375 0 5 7 8 3 5 8 7 3 A./B
18 6 3 2 6 3 A.*B
3 4 3 8 6 4 B A
9 12 3 8 6 4 B A
3 2 6 3 8 b A
9 7 3 6 4 b A
= =
= =
= =
= =
= =
=
=
= + + +
=
= + + +
ElementbyElementOperations
But a*b gives an error (undefined) because
dimensions are incorrect. Need to use .*
VectorandMatrixoperations
(
(
(

= +
(
(
(

=
(
(
(

=
11
7
3
b a
6
4
2
b
5
3
1
a
(
(
(

=
(
(
(

=
30
12
2
6 * 5
4 * 3
2 * 1
b .* a
VectorizedMatrixOperations
9 243 81 3 B ).^ 3 ( F
1 512 27 8 3 .^ A E
5 . 0 6 . 1 75 . 0 2 B / . A D
2 40 12 2 B .* A C
2 5 4 1 B
1 8 3 2 A
= =
= =
= =
= =
=
=
ArrayOperationsfor
m nMatrices
(
(
(

= =
5 10 5 15
20 15 10 5
20 15 10 5
5 .* A B
| |
(
(
(

= =
1 2 1 3
4 3 2 1
4 3 2 1
1 - 2 1 3 -4; : -1 : 1 - 4; : 1 A
(
(
(

= =
1 8 1 27
64 27 8 1
64 27 8 1
3 .^ A C
MatrixTranspose
| | | |
| |
| | 4 ) 2 ( 3 ) 1 )( 2 ( ) 3 )( 4 (
2 -
1
3
3 2 4 ' y * x
6 3 9
4 2 6
8 4 12
2 1 3
3
2
4
y '* x
2 -
1
3
y' ;
3
2
4
' x
2 1 3 y ; 3 2 4 x
= + + =
(
(
(

=
(
(
(



=
(
(
(

=
(
(
(

=
(
(
(

=
= =
BuiltinFunctions
BuiltinFunctions
Allthestandardoperators+,,*,/,^
Sqrt( ), abs( ), sin( ), cos( ), exp( ),
tanh( ), acos( ), log( ), log10( ), etc.
Theseoperatorsarevectorized
(
(
(

=
(
(
(

=
(
(
(

=
exp(4)
exp(5)
exp(3)
exp(a) ;
sin(4)
sin(5)
sin(3)
) a sin( ;
4
5
3
a
BuiltinFunctions
Certainfunctions,suchasexponentialandsquare
root,havematrixdefinitionalso
Usehelp expm andhelp sqrtm fordetails
>> A = [1 3 5; 2 4 6; -3 2 -1]
A =
1 3 5
2 4 6
-3 2 -1
>> B = sqrt(A)
B =
1.0000 1.7321 2.2361
1.4142 2.0000 2.4495
0 + 1.7321i 1.4142 0 + 1.0000i
>> C = sqrtm(A)
C =
2.1045 + 0.0000i 0.1536 - 0.0000i 1.8023 + 0.0000i
1.7141 - 0.0000i 1.1473 + 0.0000i 1.7446 + 0.0000i
-2.0484 + 0.0000i 1.3874 + 0.0000i 0.5210 - 0.0000i
(element by element)
(C*C = A)
InputOutput
input allowtoprompttheuserforvalues
directlyfromthecommandwindow
disp provideahandywaytodisplaya
value
fprintf provideadditionalcontroloverthe
displayofinformation
Requiretheuseoftheformatcode(nextpage)
Prototype:fprinf(format,x,)
Commonlyusedformatandcontrol
codeswiththefprintf function
Thefprintf(format,data) function
FormatCode
%d integer
%f floatingpointformat
%e exponentialformatwithlowercase
%Eexponentialwithuppercase
%g eitherfloatingpointorexponential
format,whicheverisshorter
Controlcode
\n newlinecharacter
\t tabcharacter
Tricktoforcethatdisplayshowthe
decimalplacewewant
>>disp(pi)
>>disp(round(pi*100)/100)
Examplewithfprintf
velocity=1000/81;
fprintf(thevelocityis%8.4fm/s\n,velocity)
SeeMatlabhelpforfprintf
Creatingandaccessingfiles
Savingdatainafile:
savefilename variable_1 variable_2 variable_n
Obtainingthedatafromafile
loadfilename variable_1 variable_2 variable_n
Importantdetail:Wherethedataissaved?
Example
g=9.81;m=80;t=5;
cd=[0.250.2670.2450.280.273];
v=sqrt(g*m./cd).*tanh(sqrt(g*cd/m)*t);
saveveldrag v cd
clear
loadveldrag v cd
Exchangingdatawithexcel
[data,heading,raw]=xlsread(filename,sheet,range)
xlswrite(filename,data,sheetName,Initialrange)

You might also like