Introduction to MATLAB

advertisement
UniversityCollegeofSoutheastNorway
MATLAB
PartI:IntroductiontoMATLAB
Hans-PetterHalvorsen,2016.06.20
http://home.hit.no/~hansha
Preface
InthisMATLABCourseyouwilllearnbasicMATLABandhowtouseMATLABinControland
Simulationapplications.AnintroductiontoSimulinkandotherToolswillalsobegiven.
MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegrated
environment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedfor
matrixmanipulationandproblemsolvingrelatedtoLinearAlgebra, Modelling,Simulation
andControlapplications.
Thisisaself-pacedcoursebasedonthisdocumentandsomeshortvideosontheway.This
documentcontainslotsofexamplesandself-pacedtasksthattheuserswillgothroughand
solveontheirown.Theusermaygothroughthetasksinthisdocumentintheirownpace
andtheinstructorwillbeavailableforguidancethroughoutthecourse.
TheMATLABCourseconsistsof3parts:
•
•
•
MATLABCourse–PartI:IntroductiontoMATLAB
MATLABCourse–PartII:Modelling,SimulationandControl MATLABCourse–PartIII:SimulinkandAdvancedTopics
InPartIofthecourse(PartI:Introduction–MATLABBasics)youwillbefamiliarwiththe
MATLABenvironmentandlearnbasicMATLABprogramming.
ThecourseconsistsoflotsofTasksyoushouldsolvewhilereadingthiscoursemanualand
watchingthevideosreferredtointhetext.
Makesuretobringyourheadphonesforthevideosinthiscourse.Thecourse
consistsofseveralshortvideosthatwillgiveyouanintroductiontothedifferenttopicsin
thecourse.
Prerequisites Youshouldbefamiliarwithundergraduate-levelmathematicsandhaveexperiencewith
basiccomputeroperations.
WhatisMATLAB?MATLABisatoolfortechnicalcomputing,computationandvisualization
inanintegratedenvironment.MATLABisanabbreviationforMATrixLABoratory,soitiswell
suitedformatrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.
ii
MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.
MATLABisinuseworld-widebyresearchersanduniversities.Formoreinformation,see
www.mathworks.com
FormoreinformationaboutMATLAB,etc.,pleasevisithttp://home.hit.no/~hansha/
iii
TableofContents
Preface......................................................................................................................................ii
TableofContents.....................................................................................................................iv
1
Introduction......................................................................................................................1
2
TheMATLABEnvironment................................................................................................2
2.1
CommandWindow....................................................................................................3
2.2
CommandHistory......................................................................................................4
2.3
Workspace.................................................................................................................4
2.4
CurrentFolder...........................................................................................................6
2.5
Editor.........................................................................................................................7
3
UsingtheHelpSysteminMATLAB....................................................................................9
4
MATLABBasics................................................................................................................11
4.1
BasicOperations......................................................................................................11
Task1: BasicOperations..........................................................................................13
Task2: Statisticsfunctions.......................................................................................14
4.2
Arrays;VectorsandMatrices..................................................................................15
4.2.1
ColonNotation................................................................................................16
Task3: VectorsandMatrices...................................................................................17
4.3
TipsandTricks.........................................................................................................18
4.3.1
5
ArrayOperations.............................................................................................19
LinearAlgebra;VectorsandMatrices.............................................................................22
5.1
Vectors....................................................................................................................22
5.2
Matrices...................................................................................................................23
5.2.1
Transpose........................................................................................................24
iv
v
TableofContents 5.2.2
Diagonal...........................................................................................................24
5.2.3
Triangular........................................................................................................25
5.2.4
MatrixMultiplication.......................................................................................25
5.2.5
MatrixAddition...............................................................................................26
5.2.6
Determinant....................................................................................................27
5.2.7
InverseMatrices..............................................................................................28
5.3
Eigenvalues..............................................................................................................29
Task4: Matrixmanipulation....................................................................................29
5.4
SolvingLinearEquations..........................................................................................30
Task5: LinearEquations..........................................................................................30
6
M-files;Scriptsanduser-definefunctions.......................................................................33
6.1
Scriptsvs.functionFiles..........................................................................................33
6.2
Scripts......................................................................................................................34
Task6: Script............................................................................................................36
6.3
Functions.................................................................................................................37
Task7: User-definedfunction.................................................................................40
Task8: User-definedfunction.................................................................................40
7
Plotting............................................................................................................................41
Task9: Plotting........................................................................................................42
7.1
PlottingMultipleDataSetsinOneGraph...............................................................43
Task10:
7.2
Plotofdynamicsystem...........................................................................44
DisplayingMultiplePlotsinoneFigure–Sub-Plots................................................45
Task11:
Sub-plots..................................................................................................46
7.3
Custimizing..............................................................................................................46
7.4
OtherPlots..............................................................................................................50
Task12:
OtherPlots...............................................................................................50
MATLAB Course - Part I: Introduction to MATLAB
vi
8
FlowControl....................................................................................................................51
8.1
FlowControl............................................................................................................51
8.2
If-elseStatement.....................................................................................................51
Task13:
8.3
8.4
FibonacciNumbers..................................................................................55
Whileloop...............................................................................................................56
Task16:
8.6
Switch-CaseStatements..........................................................................54
Forloop...................................................................................................................55
Task15:
8.5
If-elseStatements....................................................................................53
SwitchandCaseStatement.....................................................................................54
Task14:
9
TableofContents WhileLoop...............................................................................................57
AdditionalTasks......................................................................................................57
Task17:
ForLoops.................................................................................................57
Task18:
If-elseStatement.....................................................................................57
Mathematics...................................................................................................................59
9.1
BasicMathFunctions..............................................................................................59
Task19:
9.2
Statistics..................................................................................................................59
Task20:
9.3
9.4
BasicMathfunction.................................................................................59
Statistics...................................................................................................59
TrigonometricFunctions.........................................................................................59
Task21:
Conversion...............................................................................................60
Task22:
Trigonometricfunctionsonrighttriangle...............................................60
Task23:
Lawofcosines..........................................................................................61
Task24:
Plotting....................................................................................................62
ComplexNumbers...................................................................................................62
Task25:
Complexnumbers....................................................................................64
Task26:
Complexnumbers....................................................................................65
MATLAB Course - Part I: Introduction to MATLAB
vii
9.5
10
TableofContents Polynomials.............................................................................................................65
Task27:
Polynomials.............................................................................................65
Task28:
Polynomials.............................................................................................66
Task29:
PolynomialFitting....................................................................................66
AdditionalTasks..........................................................................................................67
Task30:
User-definedfunction..............................................................................67
Task31:
MATLABScript.........................................................................................67
Task32:
Cylindersurfacearea...............................................................................68
Task33:
CreateadvancedexpressionsinMATLAB................................................68
Task34:
SolvingEquations.....................................................................................69
Task35:
Preallocatingofvariablesandvectorization............................................69
Task36:
NestedForLoops.....................................................................................70
AppendixA:MATLABFunctions..............................................................................................72
Built-inConstants................................................................................................................72
BasicFunctions....................................................................................................................72
LinearAlgebra.....................................................................................................................73
Plotting................................................................................................................................73
LogicalOperators................................................................................................................74
ComplexNumbers...............................................................................................................74
MATLAB Course - Part I: Introduction to MATLAB
1 Introduction
PartI:IntroductiontoMATLABconsistsofthefollowingtopics:
•
•
•
•
•
•
•
•
•
TheMATLABEnvironment
UsingtheHelpSysteminMATLAB
MATLABBasics
LinearAlgebra;VectorsandMatrices
Mfiles;ScriptsandUser-definedfunctions
Plotting
FlowControl;ForandWhileLoops,IfandCasestatements
Mathematics
AdditionalTasks
1
2 TheMATLABEnvironment
TheMATLABEnvironmentconsistsofthefollowingmainparts:
•
•
•
•
•
CommandWindow
CommandHistory
Workspace
CurrentFolder
Editor
BelowweseetheMATLABenvironment:
Beforeyoustart,youshouldwatchthevideo“WorkingintheDevelopment
Environment”.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?lab=matlab
2
3
TheMATLABEnvironment 2.1 CommandWindow
TheCommandWindowisthemainwindowinMATLAB.UsetheCommandWindowtoenter
variablesandtorunfunctionsandM-filesscripts(moreaboutm-fileslater).
YoutypeallyourcommandsafterthecommandPrompt“>>”,e.g.,definingthefollowing
matrix:
𝐴=
1 2
0 3
TheMATLABsyntaxisasfollows:
>> A = [1 2;0 3]
Or
>> A = [1,2;0,3]
Ifyou,foranexample,wanttofindtheanswerto
𝑎 + 𝑏, 𝑤ℎ𝑒𝑟𝑒𝑎 = 4, 𝑏 = 3
Typelikethis:
>>a = 4
>>b = 3
>>a + b
MATLABthenresponds:
MATLAB Course - Part I: Introduction to MATLAB
4
TheMATLABEnvironment ans =
7
2.2 CommandHistory
StatementsyouenterintheCommandWindowareloggedintheCommandHistory.From
theCommandHistory,youcanviewandsearchforpreviouslyrunstatements,aswellas
copyandexecuteselectedstatements.YoucanalsocreateanM-filefromselected
statements.
2.3 Workspace
TheWorkspacewindowlistallyourvariablesusedaslongyouhaveMATLABopened.
MATLAB Course - Part I: Introduction to MATLAB
5
TheMATLABEnvironment Youcouldalsousethefollowingcommand
>>who
Thiscommandlistallthecommandsused
or
>>whos
Thiscommandlistsallthecommandwiththecurrentvalues,dimensions,etc.
Thecommandclear,willclearallthevariablesinyourworkplace.
>>clear
Saveyourdata:
Youmayalsosaveallyourvariablesanddatatoatextfile(.matfile),thisisusefulifyou
wanttosaveyourdataanduseitforlater.
Selectthevariablesyouwanttosaveandright-clickandselect“SaveAs…”:
MATLAB Course - Part I: Introduction to MATLAB
6
TheMATLABEnvironment MATLABalsohavecommandsforthis:save/loadanddiary.
2.4 CurrentFolder
The“CurrentFolder”windowlistsallmfiles,etc.availableinthecurrentdirectory.
MATLAB Course - Part I: Introduction to MATLAB
7
TheMATLABEnvironment YoushouldsetyourworkingfolderastheCurrentDirectoryorsetyourworkingfolderas
partofthesearchpath,ifyoudon’tMATLABwillnotfindyourfiles.
SearchPath:
YouneedtousethisifyouwantMATLABtofindyourscriptsandfunctionsyouwanttouse.
2.5 Editor
TheEditorisusedtocreatescriptsandm-files.Clickthe“NewScript”buttonintheToolbar MATLAB Course - Part I: Introduction to MATLAB
8
TheMATLABEnvironment Whenyoulearnaboutm-files(scriptsandfunctions)inalaterchapteryouwillbeusingthis
editortoenteryourcommandsandsavethem.
Note!Inthebeginningofthecourse(chapter1-5)wewillonlyusetheCommandWindow.
Inchapter6wewillstartusingtheEditor. MATLAB Course - Part I: Introduction to MATLAB
3 UsingtheHelpSystemin
MATLAB
TheHelpsysteminMATLABisquitecomprehensive,somakesureyouarefamiliarwithhow
thehelpsystemworks.
whenclickingthe“Help”button,thefollowingwindowappears:
Youmayalsotype“Help”intheCommandwindow:
9
10
UsingtheHelpSysteminMATLAB MATLABanswerswithlinkstolotsofHelptopics.Youmayalsotypemorespecific,e.g.,
“Helpelfun”(ElementaryMathFunctions),andMATLABwilllistallfunctionsaccordingto
thespecificcategory.
Ifyoutype“help<functionname>”youwillgetspecifichelpaboutthisfunction.
Youmayalsotype“doc<topic>”toopentheHelpwindowonthespecifictopicofinterest.
Searching:
Wecanusethehelpkeywordwhenwewanttogethelpforaspecificfunction,butifwe
wanttosearchforallfunctions,etc.withaspecifickeywordyoumayusethelookfor
command.
Example:
lookfor plot
[EndofExample]
MATLAB Course - Part I: Introduction to MATLAB
4 MATLABBasics
Beforeyoustart,youshouldwatchthevideo“GettingStartedwithMATLAB”
Thevideoisavailablefrom:http://home.hit.no/~hansha/?lab=matlab
4.1 BasicOperations
Variables:
Variablesaredefinedwiththeassignmentoperator,“=”.MATLABisdynamicallytyped,
meaningthatvariablescanbeassignedwithoutdeclaringtheirtype,andthattheirtypecan
change.Valuescancomefromconstants,fromcomputationinvolvingvaluesofother
variables,orfromtheoutputofafunction. Example:
>> x = 17
x =
17
>> x = 'hat'
x =
hat
>> x = [3*4, pi/2]
x =
12.0000
1.5708
>> y = 3*sin(x)
y =
-1.6097
3.0000
[EndofExample]
Note!MATLABiscasesensitive!Thevariables 𝑥 and 𝑋 arenotthesame.
Note!Unlikemanyotherlanguages,wherethesemicolonisusedtoterminatecommands,in
MATLABthesemicolonservestosuppresstheoutputofthelinethatitconcludes.
>> a=5
a =
5
11
12
MATLABBasics >> a=6;
>>
Asyousee,whenyoutypeasemicolon(;)afterthecommand,MATLABwillnotrespond.
ThisisveryusefulbecausesometimesyouwantMATLABtorespond,whileinother
situationsthatisnotnecessary.
Built-inconstants:
MATLABhaveseveralbuilt-inconstants.Someofthemareexplainedhere:
Name
Description
Usedforcomplexnumbers,e.g.,z=2+4i
𝜋
∞,Infinity
NotANumber.Ifyou,e.g.,dividebyzero,yougetNaN
i, j
pi
inf
NaN
NamingaVariableUniquely:
Toavoidchoosinganameforanewvariablethatmightconflictwithanamealreadyinuse,
checkforanyoccurrencesofthenameusingthewhichcommand:
which
-all
variablename
Example:
>> which -all pi
built-in (C:\Matlab\R2007a\toolbox\matlab\elmat\pi)
Youmayalsousetheiskeywordcommand.ThiscommandcausesMATLABtolistall
reservednames.
>> iskeyword
ans =
'break'
'case'
'catch'
'classdef'
'continue'
'else'
'elseif'
'end'
'for'
MATLAB Course - Part I: Introduction to MATLAB
13
MATLABBasics 'function'
'global'
'if'
'otherwise'
'persistent'
'return'
'switch'
'try'
'while'
Note!Youcannotassignthesereservednamesasyourvariablenames.
Note!MATLABallowsyoutoreassignbuilt-infunctionnamesasvariablenames,butthatis
notrecommended!–sobecarefullywhenyouselectthenameofyourvariables!
Example:
>> sin=4
sin =
4
>> sin(3)
??? Index exceeds matrix dimensions.
Inthisexampleyouhavedefinedavariable“sin”–but“sin”isalsoabuilt-infunction–and
thisfunctionwillnolongerwork!
Ifyouaccidentlydoso,usetheclearcommandtoresetitbacktonormal.
[EndofExample]
Task1:
BasicOperations
TypethefollowingintheCommandwindow:
>>y=16;
>>z=3;
>>y+z
Note!Whenyouuseasemicolon,nooutputwillbedisplayed.Trythecodeabovewithand
withoutsemicolon.
Note!Somefunctionsdisplayoutputevenifyouusesemicolon,likedisp,plot,etc.
Otherbasicoperationsare:
MATLAB Course - Part I: Introduction to MATLAB
14
MATLABBasics >>16-3
>>16/3
>>16*3
→Trythem.
[EndofTask]
Built-inFunctions:
Herearesomedescriptionsforthemostusedbasicbuilt-inMATLABfunctions.
Function
help
help
<function>
who,whos
clear
size
length
format
disp
plot
clc
rand
max
min
mean
std
Description
Example
MATLABdisplaysthehelpinformationavailable
>>help
Displayhelpaboutaspecificfunction
>>help plot
wholistsinalphabeticalorderallvariablesinthecurrently
activeworkspace.
Clearvariablesandfunctionsfrommemory.
>>who
>>whos
Sizeofarrays,matrices
Lengthofavector
>>clear
>>clear x
>>x=[1 2 ; 3 4];
>>size(A)
>>x=[1:1:10];
>>length(x)
Setoutputformat
Displaytextorarray
Thisfunctionisusedtocreateaplot
CleartheCommandwindow
Createsarandomnumber,vectorormatrix
Findthelargestnumberinavector
Findthesmallestnumberinavector
Averageormeanvalue
Standarddeviation
>>A=[1 2;3 4];
>>disp(A)
>>x=[1:1:10];
>>plot(x)
>>y=sin(x);
>>plot(x,y)
>>cls
>>rand
>>rand(2,1)
>>x=[1:1:10]
>>max(x)
>>x=[1:1:10]
>>min(x)
>>x=[1:1:10]
>>mean(x)
>>x=[1:1:10]
>>std(x)
Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthese
functions.Type“help<functionname>”intheCommandwindow.
Task2:
Statisticsfunctions
Createarandomvectorwith100randomnumbersbetween0and100.Findtheminimum
value,themaximumvalue,themeanandthestandarddeviationusingsomeofthebuilt-in
functionsinMATLABlistedabove.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
15
MATLABBasics 4.2 Arrays;VectorsandMatrices
Beforeyoustart,youshouldwatchthevideo“WorkingwithArrays”.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?lab=matlab
Matricesandvectors(LinearAlgebra)arethebasicelementsinMATLABandalsothebasic
elementsincontroldesigntheory.Soitisimportantyouknowhowtohandlevectorsand
matricesinMATLAB.
Ageneralmatrix 𝐴 maybewrittenlikethis:
𝑎55
𝐴= ⋮
𝑎:5
⋯
⋱
⋯
𝑎57
⋮ ∈ 𝑅:=7 𝑎:7
InMATLABwetypevectorsandmatriceslikethis:
𝐴=
1 2
3 4
>> A = [1 2; 3 4]
A =
1
3
2
4
or:
>> A = [1, 2; 3, 4]
A =
1
3
2
4
→Toseparaterows,weuseasemicolon“;”
→Toseparatecolumns,weuseacomma“,”oraspace““.
Togetaspecificpartofamatrix,wecantypelikethis:
>> A(2,1)
ans =
3
or:
>> A(:,1)
ans =
MATLAB Course - Part I: Introduction to MATLAB
16
MATLABBasics 1
3
or:
>> A(2,:)
ans =
3
4
From2vectorsxandywecancreateamatrixlikethis:
>> x
>> y
>> B
B =
= [1; 2; 3];
= [4; 5; 6];
= [x y]
1
4
2
5
3
6
4.2.1
ColonNotation
The“colonnotation”isveryusefulforcreatingvectors:
Example:
Thisexampleshowshowtousethecolonnotationcreatingavectoranddosome
calculations.
MATLAB Course - Part I: Introduction to MATLAB
17
MATLABBasics [EndofExample]
Task3:
VectorsandMatrices
TypethefollowingvectorintheCommandwindow:
1
𝑥= 2
3
TypethefollowingmatrixintheCommandwindow:
𝐴=
0
1
−2 −3
TypethefollowingmatrixintheCommandwindow:
𝐶=
−1 2
0
4 10 −2 1
0
6
→UseUseMATLABtofindthevalueinthesecondrowandthethirdcolumnofmatrix 𝐶.
→UseMATLABtofindthesecondrowofmatrix 𝐶.
→UseMATLABtofindthethirdcolumnofmatrix 𝐶.
[EndofTask]
DeletingRowsandColumns:
Youcandeleterowsandcolumnsfromamatrixusingjustapairofsquarebrackets[]. Example:
MATLAB Course - Part I: Introduction to MATLAB
18
MATLABBasics Given:
𝐴=
0
1
−2 −3
Todeletethesecondcolumnofamatrix 𝐴,use:
>>A=[0 1; -2 -3];
>>A(:,2) = []
A =
0
-2
[EndofExample]
4.3 TipsandTricks
Namingconversions:
Whencreatingvariablesandconstants,makesureyoucreateanamethatisnotalready
existsinMATLAB.NotealsothatMATLABiscasesensitive!ThevariablesxandXarenotthe
same.
Usethewhichcommandtocheckifthenamealreadyexists:which –all <your
name>
Example:
>> which -all sin
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@double\sin)
double method
%
built-in (C:\Matlab\R2007a\toolbox\matlab\elfun\@single\sin)
single method
%
Largeorsmallnumbers:
Ifyouneedtowritelargeorsmallnumbers,like 2𝑥10A , 7.5𝑥10EF youcanusethe“e”
notation,e.g.:
>> 2e5
ans =
200000
>> 7.5e-8
MATLAB Course - Part I: Introduction to MATLAB
19
MATLABBasics ans =
7.5000e-008
LineContinuation:
Forlargearrays,itmaybedifficulttofitonerowononecommandline.Wemaythensplit
therowacrossseveralcommandlinesbyusingthelinecontinuationoperator“...”.
Example:
>> x=[1 2 3 4 5 ...
6 7 8 9 10]
x =
1
2
3
4
5
6
7
8
9
10
Multiplecommandsonsameline:
Itispossibletotypeseveralcommandsonthesameline.Insomecasesthisisagoodideato
savespace.
Example:
>> x=1,y=2,z=3
x =
1
y =
2
z =
3
4.3.1
ArrayOperations
Wehavethefollowingbasicmatrixoperations:
MATLAB Course - Part I: Introduction to MATLAB
20
MATLABBasics Thebasicmatrixoperationscanbemodifiedforelement-by-elementoperationsby
precedingtheoperatorwithaperiod.Themodifiedoperationsareknownasarray
operations.
Given
𝑎55
𝐴= 𝑎
G5
𝑎5G
𝑏55
,
𝐵
=
𝑎GG
𝑏G5
𝑏5G
𝑏GG
Then
𝐴.∗ 𝐵 =
𝑎55 𝑏55
𝑎G5 𝑏G5
𝑎5G 𝑏5G
𝑎GG 𝑏GG
TheelementsofA.*BaretheproductsofthecorrespondingelementsofAandB.
Wehavethefollowingarrayoperators:
Example:
>> A = [1; 2; 3]
A =
1
2
3
>> B = [-6; 7; 10]
B =
-6
7
10
>> A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> A.*B
ans =
MATLAB Course - Part I: Introduction to MATLAB
21
-6
14
30
[EndofExample]
MATLAB Course - Part I: Introduction to MATLAB
MATLABBasics 5 LinearAlgebra;Vectorsand
Matrices
LinearAlgebraisabranchofmathematicsconcernedwiththestudyofmatrices,vectors,
vectorspaces(alsocalledlinearspaces),linearmaps(alsocalledlineartransformations),and
systemsoflinearequations.
MATLABarewellsuitedforLinearAlgebra.Thischapterassumesyouhavesomebasic
understandingofLinearAlgebraandmatricesandvectors.
HerearesomeusefulfunctionsforLinearAlgebrainMATLAB:
Function
rank
det
inv
eig
ones
eye
diag
Description
Example
Findtherankofamatrix.Providesanestimateofthenumber
oflinearlyindependentrowsorcolumnsofamatrixA.
Findthedeterminantofasquarematrix
Findtheinverseofasquarematrix
Findtheeigenvaluesofasquarematrix
Createsanarrayormatrixwithonlyones
>>A=[1 2; 3 4]
>>rank(A)
>>A=[1 2; 3 4]
>>det(A)
>>A=[1 2; 3 4]
>>inv(A)
>>A=[1 2; 3 4]
>>eig(A)
>>ones(2)
>>ones(2,1)
>>eye(2)
Createsanidentitymatrix
Findthediagonalelementsinamatrix
>>A=[1 2; 3 4]
>>diag(A)
Type“helpmatfun”(Matrixfunctions-numericallinearalgebra)intheCommandWindow
formoreinformation,ortype“helpelmat”(Elementarymatricesandmatrixmanipulation).
Youmayalsotype“help<functionname>”forhelpaboutaspecificfunction.
Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthese
functions.Type“help<functionname>”intheCommandwindow.
5.1 Vectors
Givenavector 𝑥:
𝑥5
𝑥G
𝑥 = ⋮ ∈ 𝑅: 𝑥:
22
23
LinearAlgebra;VectorsandMatrices Example:
Given:
1
𝑥= 2
3
>> x=[1; 2; 3]
x =
1
2
3
TheTransposeofvectorx:
𝑥 J = 𝑥5
>> x'
ans =
1
2
𝑥G
⋯
𝑥: ∈ 𝑅5=: 3
TheLengthofvectorx:
𝑥 =
𝑥5G + 𝑥GG + ⋯ + 𝑥:G 𝑥J𝑥 =
Orthogonality:
𝑥 J 𝑦 = 0
[EndofExample]
5.2 Matrices
Givenamatrix 𝐴:
𝑎55
𝐴= ⋮
𝑎:5
⋯
⋱
⋯
𝑎57
⋮ ∈ 𝑅:=7 𝑎:7
Example:
𝐴=
0
1
−2 −3
MATLAB Course - Part I: Introduction to MATLAB
24
LinearAlgebra;VectorsandMatrices >> A=[0 1;-2 -3]
A =
0
1
-2
-3
[EndofExample]
5.2.1
Transpose
TheTransposeofmatrix 𝐴:
𝑎55
𝐴 = ⋮
𝑎57
J
⋯
⋱
⋯
𝑎:5
⋮ ∈ 𝑅7=: 𝑎:7
Example:
𝐴J =
>> A'
ans =
0
-2
1
-3
0
1
−2 −3
J
=
0 −2
1 −3
[EndofExample]
5.2.2
Diagonal
TheDiagonalelementsofmatrixAisthevector
𝑎55
𝑎GG
𝑑𝑖𝑎𝑔(𝐴) = ⋮ ∈ 𝑅QRSTU(=,7) 𝑎QQ
Example:
>> diag(A)
ans =
0
-3
[EndofExample]
MATLAB Course - Part I: Introduction to MATLAB
25
LinearAlgebra;VectorsandMatrices TheDiagonalmatrixΛisgivenby:
𝜆5
0
Λ=
⋮
0
0
𝜆G
⋮
0
⋯
⋯
⋱
⋯
0
0
∈ 𝑅:=: ⋮
𝜆:
GiventheIdentitymatrixI:
1 0 ⋯
0 1 ⋯
𝐼=
⋮ ⋮ ⋱
0 0 ⋯
0
0
∈ 𝑅:=7 ⋮
1
Example:
>> eye(3)
ans =
1
0
0
0
1
0
0
0
1
[EndofExample]
5.2.3
Triangular
LowerTriangularmatrixL:
. 0
𝐿= ⋮ ⋱
. ⋯
0
0
.
. ⋯
0
⋱
𝑈=
0 0
.
⋮
.
UpperTriangularmatrixU:
5.2.4
MatrixMultiplication
Giventhematrices 𝐴 ∈ 𝑅:=7 and 𝐵 ∈ 𝑅7=Q ,then
𝐶 = 𝐴𝐵 ∈ 𝑅:=Q where
MATLAB Course - Part I: Introduction to MATLAB
26
LinearAlgebra;VectorsandMatrices :
𝑎\^ 𝑏^] 𝑐\] =
^R5
Example:
>> A = [0 1;-2 -3]
A =
0
1
-2
-3
>> B = [1 0;3 -2]
B =
1
0
3
>> A*B
ans =
3
-11
-2
-2
6
→Checktheanswerbymanuallycalculatingusingpen&paper.
[EndofExample]
Note!
Note!
𝐴𝐵 ≠ 𝐵𝐴
𝐴 𝐵𝐶 = 𝐴𝐵 𝐶
𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵
5.2.5
MatrixAddition
Giventhematrices 𝐴 ∈ 𝑅:=7 and 𝐵 ∈ 𝑅:=7 ,then
MATLAB Course - Part I: Introduction to MATLAB
27
LinearAlgebra;VectorsandMatrices 𝐶 = 𝐴 + 𝐵 ∈ 𝑅:=7 Example:
>> A = [0 1;-2 -3]
>> B = [1 0;3 -2]
>> A + B
ans =
1
1
1
-5
→Checktheanswerbymanuallycalculatingusingpen&paper.
[EndofExample]
5.2.6
Determinant
Givenamatrix 𝐴 ∈ 𝑅:=: ,thentheDeterminantisgivenby:
𝑑𝑒𝑡 𝐴 = 𝐴 Givena 2𝑥2 matrix:
𝑎55
𝐴= 𝑎
G5
𝑎5G
G=G
𝑎GG ∈ 𝑅 Then
𝑑𝑒𝑡 𝐴 = 𝐴 = 𝑎55 𝑎GG − 𝑎G5 𝑎5G Example:
A =
0
1
-2
-3
>> det(A)
ans =
2
→Checktheanswerbymanuallycalculatingusingpen&paper.
[EndofExample]
MATLAB Course - Part I: Introduction to MATLAB
28
LinearAlgebra;VectorsandMatrices Noticethat
det 𝐴𝐵 = det 𝐴 det 𝐵 and
det 𝐴J = det(𝐴)
Example:
>> det(A*B)
ans =
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
ans =
2
[EndofExample]
5.2.7
InverseMatrices
Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅:=: isdefinedby:
𝐴E5 if
𝐴𝐴E5 = 𝐴E5 𝐴 = 𝐼
Fora 2𝑥2 matrixwehave:
𝑎55
𝐴= 𝑎
G5
𝑎5G
G=G
𝑎GG ∈ 𝑅 Theinverse 𝐴E5 isthengivenby
𝐴E5 =
1
𝑎GG
𝑑𝑒𝑡(𝐴) −𝑎G5
−𝑎5G
G=G
𝑎55 ∈ 𝑅 Example:
A =
0
1
MATLAB Course - Part I: Introduction to MATLAB
29
-2
LinearAlgebra;VectorsandMatrices -3
>> inv(A)
ans =
-1.5000
-0.5000
1.0000
0
→Checktheanswerbymanuallycalculatingusingpen&paper.
Noticethat:
𝐴𝐴E5 = 𝐴E5 𝐴 = 𝐼
[EndofExample]
5.3 Eigenvalues
Given 𝐴 ∈ 𝑅:=: ,thentheEigenvaluesisdefinedas:
𝑑𝑒𝑡 𝜆𝐼 − 𝐴 = 0
Example:
A =
0
1
-2
-3
>> eig(A)
ans =
-1
-2
→Checktheanswerbymanuallycalculatingusingpen&paper.
[EndofExample]
Task4:
Matrixmanipulation
Inthistaskwewillpracticeonenteringmatricesandperformbasicmatrixoperations.
Giventhematrices 𝐴, 𝐵 and 𝐶:
𝐴=
0
1
,
−2 −3
𝐵=
1 0
,
3 −2
𝐶=
→SolvethefollowingbasicmatrixoperationsusingMATLAB:
MATLAB Course - Part I: Introduction to MATLAB
1 −1
−2 2
30
•
•
•
•
•
•
•
•
LinearAlgebra;VectorsandMatrices 𝐴 + 𝐵
𝐴 − 𝐵
𝐴J 𝐴E5 𝑑𝑖𝑎𝑔 𝐴 , 𝑑𝑖𝑎𝑔(𝐵)
𝑑𝑒𝑡 𝐴 , 𝑑𝑒𝑡(𝐵)
𝑑𝑒𝑡 𝐴𝐵 𝑒𝑖𝑔 𝐴 whereeig=Eigenvalues,diag=Diagonal,det=Determinant
→UseMATLABto“prove”thefollowing:
•
•
•
•
•
•
•
𝐴𝐵 ≠ 𝐵𝐴
𝐴 𝐵𝐶 = 𝐴𝐵 𝐶
𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵
det 𝐴𝐵 = det 𝐴 det 𝐵 det 𝐴J = det(𝐴)
𝐴𝐴E5 = 𝐴E5 𝐴 = 𝐼
where 𝐼 istheunitmatrix
[EndofTask]
5.4 SolvingLinearEquations
MATLABcaneasilybeusedtosolvealargeamountoflinearequationsusingbuilt-in
functions.
Task5:
LinearEquations
Giventheequations:
𝑥5 + 2𝑥G = 5
3𝑥5 + 4𝑥G = 6
Settheequationsonthefollowingform:
𝐴𝑥 = 𝑏
→Find 𝐴 and 𝑏 anddefinetheminMATLAB.
MATLAB Course - Part I: Introduction to MATLAB
31
LinearAlgebra;VectorsandMatrices Solvetheequations,i.e.,find 𝑥5, 𝑥G ,usingMATLAB.Itcanbesolvedlikethis:
𝐴𝑥 = 𝑏 → 𝑥 = 𝐴E5 𝑏
[EndofTask]
Whendealingwithlargematrices(findinginverseofAistime-consuming)ortheinverse
doesn’texistothermethodsareusedtofindthesolution,suchas:
•
•
•
LUfactorization
SingularvalueDecomposition
Etc.
InMATLABwecanalsosimplyusethebackslashoperator“\”inordertofindthesolution
likethis:
x = A\b
Example:
Giventhefollowingequations:
𝑥5 + 2𝑥G = 5
3𝑥5 + 4𝑥G = 6
7𝑥5 + 8𝑥G = 9
Fromtheequationswefind:
1 2
𝐴= 3 4 7 8
5
𝑏= 6 9
Asyoucansee,the 𝐴 matrixisnotaquadraticmatrix,meaningwecannotfindtheinverse
of 𝐴,thus 𝑥 = 𝐴E5 𝑏 willnotwork(tryitinMATLABandseewhathappens).
Sowecansolveitusingthebackslashoperator“\”:
A = [1 2; 3 4; 7 8];
b = [5;6;9];
x = A\b
MATLAB Course - Part I: Introduction to MATLAB
32
LinearAlgebra;VectorsandMatrices Actually,whenusingthebackslashoperator“\”inMATLABitusestheLUfactorizationas
partofthealgorithmtofindthesolution.
MATLAB Course - Part I: Introduction to MATLAB
6 M-files;Scriptsanduserdefinefunctions
Scriptsorm-filesaretextfilescontainingMATLABcode.UsetheMATLABEditororanother
texteditortocreateafilecontainingthesamestatementsyouwouldtypeattheMATLAB
commandline.Savethefileunderanamethatendswith“.m”.
WecaneithercreateaScriptoraFunction.Thedifferencebetweenascriptandafunction
willbeexplainedbelow.Bothwillbesavedasm-files,buttheusagewillbeslightlydifferent. Beforeyoustart,youshouldwatchthevideo“WritingaMATLABProgram”.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?lab=matlab
BelowweseetheMATLABEditorthatweusetocreateScriptsandFunctions(bothare
savedas.mfiles):
6.1 Scriptsvs.functionFiles
ItisimportanttoknowthedifferencebetweenaScriptandaFunction.
Scripts:
33
34
•
•
M-files;Scriptsanduser-definefunctions AcollectionofcommandsthatyouwouldexecuteintheCommandWindow
Usedforautomaterepetitivetasks
Functions:
•
•
•
Operateoninformation(inputs)fedintothemandreturnoutputs
Haveaseparateworkspaceandinternalvariablesthatisonlyvalidinsidethe
function
Yourownuser-definedfunctionsworkthesamewayasthebuilt-infunctionsyouuse
allthetime,suchasplot(),rand(),mean(),std(),etc.
MATLABhavelotsofbuilt-infunctions,butveryoftenweneedtocreateourownfunctions
(thesearecalleduser-definedfunctions)
BelowwewilllearnmoreaboutScriptsandFunctions.
6.2 Scripts
AScriptisacollectionofMATLABcommandsandfunctionsthatisbundledtogetherinamfile.WhenyouruntheScript,allthecommandsareexecutedsequentially. Thebuilt-inEditorforcreatingandmodifyingm-filesareshownbelow:
MATLAB Course - Part I: Introduction to MATLAB
35
M-files;Scriptsanduser-definefunctions IntheEditoryoucreateasequenceofMATLABcommandsthatyousaveasam-file(thefile
extensionendswith.m).Pushthe“Run”buttonwhenyouwanttorunyourprogram. IfthecodecontainserrorsorwarningtheMATLABcompilerwillletyouknowbydisplaying
somecolorssymbolstotherightintheEditor,asshownontheFigureabove.
Runningam-fileintheCommandwindow(justtypethenameofthem-fileandhitEnterto
runthem-file):
MATLAB Course - Part I: Introduction to MATLAB
36
M-files;Scriptsanduser-definefunctions Youmayopenoreditam-fileusingtheopenbuttoninthetoolbar.
Analternativeistotype“Edit<nameofm-file>”fromtheCommandwindow.
Task6:
Script
CreateaScript(M-file)whereyoucreateavectorwithrandomdataandfindtheaverage
andthestandarddeviation
RuntheScriptfromtheCommandwindow.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
37
M-files;Scriptsanduser-definefunctions 6.3 Functions
MATLABincludesmorethan1000built-infunctionsthatyoucanuse,butsometimesyou
needtocreateyourownfunctions.
TodefineyourownfunctioninMATLAB,usethefollowingsyntax:
function outputs = function_name(inputs)
% documentation
…
Orinmoredetail:
ThefirstlineofafunctionM-filestartswiththekeywordfunction.Itgivesthefunctionname
andorderofarguments.Inexampleabove,wehave3inputarguments(i.e, 𝑎, 𝑏, 𝑐)and2
outputarguments(i.e, 𝑥, 𝑦).
ThefirstlineofthehelptextistheH1line,whichMATLABdisplayswhenyouusethelookfor
commandorthehelpcommand.
Note!Itisrecommendedthatyouuselowercaseinthefunctionname.Youshouldneither
usespaces;useanunderscore“_”ifyouneedtoseparatewords.
AFunctioncanhaveoneormoreinputsandoneormoreoutputs.
Belowweseehowtodeclareafunctionwithoneinputandoneoutput:
Belowweseehowtodeclareafunctionwithmultipleinputsandmultipleoutputs:
MATLAB Course - Part I: Introduction to MATLAB
38
M-files;Scriptsanduser-definefunctions Example:
HereisasimpleExample:
function answer = add(x,y)
% this function adds 2 numbers
answer = x + y;
Note!Thefunctionname(add)andthenameofthefile(“add.m”)needtobeidentical.
Youmayusethefunctionlikethis:
% Example 1:
add(2,3)
% Example 2:
a = 4;
b = 6;
add(a,b);
% Example 3:
answer = add(a,b)
[EndofExample]
Youmaycreateyourownfunctionsandsavethemasam-file.FunctionsareM-filesthatcan
acceptinputargumentsandreturnoutputarguments.Functionsoperateonvariableswithin
MATLAB Course - Part I: Introduction to MATLAB
39
M-files;Scriptsanduser-definefunctions theirownworkspace,separatefromtheworkspaceyouaccessattheMATLABcommand
prompt.
Note!ThenameoftheM-fileandofthefunctionshouldbethesame!
Example:
Createafunctioncalled“linsolution”whichsolve 𝐴𝑥 = 𝑏 → 𝑥 = 𝐴E5 𝑏
Belowweseehowthem-fileforthisfunctionlookslike:
Youmaydefine 𝐴 and 𝑏 intheCommandwindowandtheusethefunctiononorderto
find 𝑥:
>> A=[1 2;3 4];
>> b=[5;6];
>> x = linsolution(A,b)
x =
-4.0000
4.5000
Afterthefunctiondeclaration(function [x] = linsolution(A,b))inthem.file,
youmaywriteadescriptionofthefunction.ThisisdonewiththeCommentsign“%”before
eachline.
FromtheCommandwindowyoucanthentype“help <function name>”inorderto
readthisinformation:
MATLAB Course - Part I: Introduction to MATLAB
40
M-files;Scriptsanduser-definefunctions >> help linsolution
Solves the problem Ax=b using x=inv(A)*b
Created By Hans-Petter Halvorsen
[EndofExample]
NamingaFunctionUniquely:
Toavoidchoosinganameforanewfunctionthatmightconflictwithanamealreadyinuse,
checkforanyoccurrencesofthenameusingthiscommand:
which
Task7:
-all
functionname
User-definedfunction
Createafunctioncalc_averagethatfindstheaverageoftwonumbers.
Testthefunctionafterwardsasfollows:
>>x = 2;
>>y = 4;
>>z = calc_average(x,y)
[EndofTask]
Task8:
User-definedfunction
Createafunctioncirclethatfindstheareainacirclebasedontheinputparameter 𝑟
(radius).
RunandtestthefunctionintheCommandwindow.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
7 Plotting
PlottingisaveryimportantandpowerfulfeatureinMATLAB.Inthischapterwewilllearn
thebasicplottingfunctionalityinMATLAB.
Plotsfunctions:Herearesomeusefulfunctionsforcreatingplots:
Function
plot
figure
subplot
grid
axis
title
xlabel
ylabel
legend
hold
Description
Example
Generatesaplot.plot(y)plotsthecolumnsofyagainstthe
indexesofthecolumns.
Createanewfigurewindow
CreatesubplotsinaFigure.subplot(m,n,p)orsubplot(mnp),
breakstheFigurewindowintoanm-by-nmatrixofsmallaxes,
selectsthep-thaxesforthecurrentplot.Theaxesarecounted
alongthetoprowoftheFigurewindow,thenthesecondrow,
etc.
Createsgridlinesinaplot.
“gridon”addsmajorgridlinestothecurrentplot.
“gridoff”removesmajorandminorgridlinesfromthecurrent
plot.
Controlaxisscalingandappearance.“axis([xminxmaxymin
ymax])”setsthelimitsforthex-andy-axisofthecurrentaxes.
Addtitletocurrentplot
title('string')
Addxlabeltocurrentplot
xlabel('string')
Addylabeltocurrentplot
ylabel('string')
Createsalegendinthecorner(orataspecifiedposition)ofthe
plot
Freezesthecurrentplot,sothatadditionalplotscanbe
overlaid
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
>>figure
>>figure(1)
>>subplot(2,2,1)
>>grid
>>grid on
>>grid off
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on
>>title('this is a title')
>> xlabel('time')
>> ylabel('temperature')
>> legend('temperature')
>>hold on
>>hold off
Type“helpgraphics”intheCommandWindowformoreinformation,ortype“help
<functionname>”forhelpaboutaspecificfunction.
Beforeyoustart,youshouldusetheHelpsysteminMATLABtoreadmoreaboutthese
functions.Type“help<functionname>”intheCommandwindow.
Example:
Hereweseesomeexamplesofhowtousethedifferentplotfunctions:
41
42
Plotting [EndofExample]
Beforeyoustartusingthesefunctions,youshouldwatchthevideo“UsingBasic
PlottingFunctions”.
Thevideoisavailablefrom:http://home.hit.no/~hansha/?lab=matlab
Task9:
Plotting
IntheCommandwindowinMATLABwindowinputthetimefrom 𝑡 = 0 secondsto 𝑡 = 10
secondsinincrementsof 0.1 secondsasfollows:
>>t = [0:0.1:10];
Then,computetheoutputyasfollows:
>>y = cos(t);
UsethePlotcommand:
>>plot(t,y)
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
43
Plotting 7.1 PlottingMultipleDataSetsinOne
Graph
InMATLABitiseasytoplotmultipledatasetinonegraph.
Example:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y, x,y2, x,y3)
Thisgivesthefollowingplot:
MATLAB Course - Part I: Introduction to MATLAB
44
Plotting Anotherapproachistousetheholdcommand:
x=0:0.01:2*pi;
plot(x, sin(x))
hold on
plot(x, cos(x))
hold off
Thisgivesthefollowingplot:
[EndofExample]
Task10:
Plotofdynamicsystem
Giventhefollowingdifferentialequation:
𝑥 = 𝑎𝑥
5
where 𝑎 = − ,where 𝑇 isthetimeconstant
J
Thesolutionforthedifferentialequationis:
MATLAB Course - Part I: Introduction to MATLAB
45
Plotting 𝑥 𝑡 = 𝑒 hi 𝑥j Set 𝑇 = 5 andtheinitialcondition 𝑥(0) = 1
→CreateaScriptinMATLAB(.mfile)whereyouplotthesolution 𝑥(𝑡) inthetimeinterval
0 ≤ 𝑡 ≤ 25
→AddGrid,andproperTitleandAxisLabelstotheplot.
[EndofTask]
7.2 DisplayingMultiplePlotsinoneFigure
–Sub-Plots
Thesubplotcommandenablesyoutodisplaymultipleplotsinthesamewindoworprint
themonthesamepieceofpaper.Typing“subplot(m,n,p)”partitionsthefigurewindowinto
anm-by-nmatrixofsmallsubplotsandselectsthepthsubplotforthecurrentplot.Theplots
arenumberedalongthefirstrowofthefigurewindow,thenthesecondrow,andsoon. Thesyntaxisasfollows:
subplot(m,n,p)
Example:
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
MATLAB Course - Part I: Introduction to MATLAB
46
Plotting subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
Thisgives:
[EndofExample]
Task11:
Sub-plots
PlotSin(x)andCos(x)in2differentsubplots.
AddTitlesandLabels.
[EndofTask]
7.3 Custimizing
Thereislotsofcustomizingyoucandowithplots,e.g.,youcanaddatitle,x-andy-axis
labels,addalegendandcustomizelinecolorsandline-styles.
Thefunctionsfordoingthisis;title,xlabel,ylabel,legend,etc.
MATLAB Course - Part I: Introduction to MATLAB
47
Plotting Example:
x=0:0.1:2*pi;
plot(x, sin(x))
%Customize the Plot:
title('This is a Title')
xlabel('This is a X label')
ylabel('This is a y label')
legend('sin(x)')
grid on
Thisgivesthefollowingplot:
[EndofExample]
Forlinecolorsandline-styleswehavethefollowingpropertieswecanusefortheplot
function:
LineStyles:
MATLAB Course - Part I: Introduction to MATLAB
48
Plotting Markerspecifiers:
Colors:
MATLAB Course - Part I: Introduction to MATLAB
49
Plotting Example:
>> x=0:0.1:2*pi;
>> plot(x, sin(x), 'r:o')
Thisgivesthefollowingplot:
[EndofExample]
MATLAB Course - Part I: Introduction to MATLAB
50
Plotting 7.4 OtherPlots
MATLABofferslotsofdifferentplots.
Task12:
OtherPlots
Checkoutthehelpforthefollowing2DfunctionsinMATLAB:loglog,semilogx,semilogy,
plotyy,polar,fplot,fill,area,bar,barh,hist,pie,errorbar,scatter.
→Trysomeofthem,e.g.,bar,histandpie.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
8 FlowControl
8.1 FlowControl
YoumayusedifferentloopsinMATLAB
•
•
Forloop
Whileloop
Ifyouwanttocontroltheflowinyourprogram,youmaywanttouseoneofthefollowing:
•
•
If-elsestatement
Switchandcasestatement
ItisassumedyouknowaboutForLoops,WhileLoops,If-ElseandSwitchstatementsfrom
otherprogramminglanguages,sowewillbrieflyshowthesyntaxusedinMATLABandgo
throughsomesimpleexamples.
8.2 If-elseStatement
The“if”statementevaluatesalogicalexpressionandexecutesagroupofstatementswhen
theexpressionistrue.Theoptional“elseif”andelsekeywordsprovidefortheexecutionof
alternategroupsofstatements.An“end”keyword,whichmatchesthe“if”,terminatesthe
lastgroupofstatements.Thegroupsofstatementsaredelineatedbythefourkeywords—no
bracesorbracketsareinvolved.
Thegeneralsyntaxisasfollows:
if expression1
statements1
elseif expression2
statements2
else
statements3
end
Example:
51
52
FlowControl Herearesomesimplecodesnippetsusingtheifsentence:
n=5
if n >
M =
elseif
M =
else
M =
end
2
eye(n)
n < 2
zeros(n)
ones(n)
or:
n=5
if n == 5
M = eye(n)
else
M = ones(n)
end
Note!Youhavetouse“if n == 5”–not”if n = 5”
[EndofExample]
Example:
if A == B, ...
Note!IfAandBarescalarsthisworks–butIfAandBarematricesthismightnotworkas
expected!
→Tryit!
Useinstead:
if isequal(A, B), ...
→Tryit!
[EndofExample]
Operators:
YoumayusethefollowingoperatorsinMATLAB:
MathematicalOperator
<
≤
>
≥
Description
LessThan
LessThanorEqualTo
GreaterThan
GreaterThanorEqualTo
MATLAB Course - Part I: Introduction to MATLAB
MATLABOperator
<
<=
>
>=
53
=
≠
EqualTo
NotEqualTo
FlowControl ==
~=
LogicalOperators:
YoumayusethefollowinglogicaloperatorsinMATLAB:
MATLABOperator
&
|
LogicalOperator
AND
OR
Task13:
If-elseStatements
Giventhesecondorderalgebraicequation:
𝑎𝑥 G + 𝑏𝑥 + 𝑐 = 0
Thesolution(roots)isasfollows:
−𝑏 ± 𝑏 G − 4𝑎𝑐
,
𝑎≠0
2𝑎
𝑐
𝑥=
− ,
𝑎 = 0, 𝑏 ≠ 0 𝑏
∅,
𝑎 = 0, 𝑏 = 0, 𝑐 ≠ 0
ℂ,
𝑎 = 0, 𝑏 = 0, 𝑐 = 0
where ∅-thereisnosolution, ℂ -anycomplexnumberisasolution
→Createafunctionthatfindsthesolutionforxbasedondifferentinputvaluesfora,band
c,e.g.,
function x = solveeq(a,b,c)
…
→Useif-elsestatementstosolvetheproblems
→TestthefunctionfromtheCommandwindowtomakesureitworksasexpected,e.g.,
>> a=0, b=2,c=1
>> solveeq(a,b,c)
Comparetheresultsusingthebuilt-infunctionroots.
Tip!For ∅,youcanjusttypedisp(‘thereisnosolution’)andfor ℂ youcantypedisp(‘any
complexnumberisasolution’)–orsomethinglikethat.
MATLAB Course - Part I: Introduction to MATLAB
54
FlowControl [EndofTask]
8.3 SwitchandCaseStatement
Theswitchstatementexecutesgroupsofstatementsbasedonthevalueofavariableor
expression.Thekeywordscaseandotherwisedelineatethegroups.Onlythefirstmatching
caseisexecuted.Theremustalwaysbeanendtomatchtheswitch.
Thegeneralsyntaxisasfollows:
switch variable
case case_value1
statements1
case case_value2
statements2
…
otherwise
statements
end
Example:
n=2
switch(n)
case 1
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
[EndofExample]
Task14:
Switch-CaseStatements
CreateafunctionthatfindseithertheAreaorthecircumferenceofacircleusingaSwitchCasestatement
Youcan,e.g.,callthefunctionlikethis:
>> r=2;
>> calccircl(r,1) % 1 means area
>> calccircl(r,2) % 2 means circumference
MATLAB Course - Part I: Introduction to MATLAB
55
FlowControl [EndofTask]
8.4 Forloop
TheForlooprepeatsagroupofstatementsafixed,predeterminednumberoftimes.A
matchingenddelineatesthestatements.
Thegeneralsyntaxisasfollows:
for variable = initval:endval
statement
...
statement
end
Example:
m=5
for n = 1:m
r(n) = rank(magic(n));
end
r
[EndofExample]
Task15:
FibonacciNumbers
Inmathematics,Fibonaccinumbersarethenumbersinthefollowingsequence:
0,1,1,2,3,5,8,13,21,34,55,89,144,…
Bydefinition,thefirsttwoFibonaccinumbersare0and1,andeachsubsequentnumberis
thesumoftheprevioustwo.Somesourcesomittheinitial0,insteadbeginningthe
sequencewithtwo1s.
Inmathematicalterms,thesequenceFnofFibonaccinumbersisdefinedbytherecurrence
relation:
𝑓: = 𝑓:E5 + 𝑓:EG withseedvalues:
𝑓j = 0, 𝑓5 = 1
MATLAB Course - Part I: Introduction to MATLAB
56
FlowControl →WriteafunctioninMATLABthatcalculatestheNfirstFibonaccinumbers,e.g.,
>> N=10;
>> fibonacci(N)
ans =
0
1
1
2
3
5
8
13
21
34
→UseaForlooptosolvetheproblem.
Fibonaccinumbersareusedintheanalysisoffinancialmarkets,instrategiessuchas
Fibonacciretracement,andareusedincomputeralgorithmssuchastheFibonaccisearch
techniqueandtheFibonacciheapdatastructure.Theyalsoappearinbiologicalsettings,
suchasbranchingintrees,arrangementofleavesonastem,thefruitletsofapineapple,the
floweringofartichoke,anuncurlingfernandthearrangementofapinecone.
[EndofTask]
8.5 Whileloop
Thewhilelooprepeatsagroupofstatementsanindefinitenumberoftimesundercontrolof
alogicalcondition.Amatchingenddelineatesthestatements.
Thegeneralsyntaxisasfollows:
while expression
statements
end
Example:
m=5;
while m > 1
m = m - 1;
zeros(m)
MATLAB Course - Part I: Introduction to MATLAB
57
FlowControl end
[EndofExample]
Task16:
WhileLoop
CreateaScriptorFunctionthatcreatesFibonacciNumbersuptoagivennumber,e.g., >> maxnumber=2000;
>> fibonacci(maxnumber)
UseaWhileLooptosolvetheproblem.
[EndofTask]
8.6 AdditionalTasks
HerearesomeadditionaltasksaboutLoopsandFlowcontrol.
Task17:
ForLoops
Extendyourcalc_averagefunctionfromaprevioustasksoitcancalculatetheaverageofa
vectorwithrandomelements.UseaForlooptoiteratethroughthevaluesinthevectorand
findsumineachiteration:
mysum = mysum + x(i);
TestthefunctionintheCommandwindow
[EndofTask]
Task18:
If-elseStatement
Createafunctionwhereyouusethe“if-else”statementtofindelementslargerthana
specificvalueinthetaskabove.Ifthisisthecase,discardthesevaluesfromthecalculated
average.
Examplediscardingnumberslargerthan10gives:
x =
4
6
12
>> calc_average(x)
MATLAB Course - Part I: Introduction to MATLAB
58
FlowControl ans =
5
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
9 Mathematics
MATLABisapowerfultoolformathematicalcalculations. Type“helpelfun”(elementaryfunctions)intheCommandwindowformoreinformation
aboutbasicmathematicalfunctions.
9.1 BasicMathFunctions
SomeBasicMathfunctionsinMATLAB:exp,sqrt,log,etc.→Lookupthesefunctionsinthe
HelpsysteminMATLAB.
Task19:
BasicMathfunction
Createafunctionthatcalculatesthefollowingmathematicalexpression:
𝑧 = 3𝑥 G + 𝑥 G + 𝑦 G + 𝑒 tU(=) Testwithdifferentvaluesonxandy.
[EndofTask]
9.2 Statistics
SomeStatisticsfunctionsinMATLAB:mean,max,min,std,etc.→Lookupthesefunctionsin
theHelpsysteminMATLAB.
Task20:
Statistics
Createavectorwithrandomnumbersbetween0and100.Findthefollowingstatistics:
mean,median,standarddeviation,minimum,maximumandthevariance.
[EndofTask]
9.3 TrigonometricFunctions
59
60
Mathematics MATLABofferslotsofTrigonometricfunctions,e.g.,sin,cos,tan,etc.→Lookupthese
functionsintheHelpsysteminMATLAB.
Note!Mostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians.
Example:
>> sin(pi/4)
ans =
0.7071
[EndofExample]
Task21:
Conversion
Sincemostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians,we
willcreateourownfunctionsinordertoconvertbetweenradiansanddegrees.
Itisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:
2𝜋 𝑟𝑎𝑑𝑖𝑎𝑛𝑠 = 360[𝑑𝑒𝑔𝑟𝑒𝑒𝑠]
Thisgives:
𝑑 𝑑𝑒𝑔𝑟𝑒𝑒𝑠 = 𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] ∙
180
𝜋
𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] = 𝑑[𝑑𝑒𝑔𝑟𝑒𝑒𝑠] ∙
𝜋
180
→Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreesto
radians(d2r(x))respectively.
Testthefunctionstomakesurethattheyworkasexpected.
[EndofTask]
Task22:
Trigonometricfunctionsonrighttriangle
Givenrighttriangle:
MATLAB Course - Part I: Introduction to MATLAB
61
Mathematics →Createafunctionthatfindstheangle 𝐴 (indegrees)basedoninputarguments (𝑎, 𝑐),
(𝑏, 𝑐) and (𝑎, 𝑏) respectively.
Use,e.g.,athirdinput“type”todefinethedifferenttypesabove.
→Useyoupreviousfunctionr2d()tomakesuretheoutputofyourfunctionisindegrees
andnotinradians.
Testthefunctionstomakesureitworksproperly.
Tip!Wehavethat:
sin 𝐴 =
𝑎
𝑎
, 𝐴 = 𝑎𝑟𝑐𝑠𝑖𝑛
𝑐
𝑐
cos 𝐴 =
𝑏
𝑏
, 𝐴 = 𝑎𝑟𝑐𝑐𝑜𝑠
𝑐
𝑐
tan 𝐴 =
𝑎
𝑎
, 𝐴 = 𝑎𝑟𝑐𝑡𝑎𝑛
𝑏
𝑏
[EndofTask]
Task23:
Lawofcosines
Given:
MATLAB Course - Part I: Introduction to MATLAB
62
Mathematics Createafunctionwhereyoufindcusingthelawofcosines.
𝑐 G = 𝑎G + 𝑏 G − 2𝑎𝑏𝑐𝑜𝑠𝐶
Testthefunctionstomakesureitworksproperly.
[EndofTask]
Task24:
Plotting
Plot 𝑠𝑖𝑛(𝜃)and 𝑐𝑜𝑠(𝜃) for 0 ≤ 𝜃 ≤ 2𝜋 inthesameplot.
Makesuretoaddlabelsandalegend,andusedifferentlinestylesandcolorsfortheplots.
[EndofTask]
9.4 ComplexNumbers
Complexnumbersareimportantinmodellingandcontroltheory.
Acomplexnumberisdefinedlikethis:
𝑧 = 𝑎 + 𝑖𝑏
or
𝑧 = 𝑎 + 𝑗𝑏
Theimaginaryunit 𝑖 or 𝑗 isdefinedas:
𝑖 = −1
Where 𝑎 iscalledtherealpartof 𝑧 and 𝑏 iscalledtheimaginarypartof 𝑧,i.e.:
𝑅𝑒(𝑧) = 𝑎, 𝐼𝑚(𝑧) = 𝑏
Youmayalsoimaginarynumbersonexponential/polarform:
𝑧 = 𝑟𝑒 \„ where:
𝑟= 𝑧 =
𝑎G + 𝑏 G 𝑏
𝜃 = 𝑎𝑡𝑎𝑛 𝑎
MATLAB Course - Part I: Introduction to MATLAB
63
Mathematics Notethat 𝑎 = 𝑟 cos 𝜃 and 𝑏 = 𝑟 sin 𝜃
Rectangularformofacomplexnumber
Exponential/polarformofacomplexnumber
Example:
Giventhefollowingcomplexnumber:
𝑧 = 2 + 𝑖3
InMATLABwemaytype:
>> z=2+3i
or:
>> z=2+3j
[EndofExample]
Thecomplexconjugateofzisdefinedas:
𝑧 ∗ = 𝑎 − 𝑖𝑏
Toaddorsubtracttwocomplexnumbers,wesimplyadd(orsubtract)theirrealpartsand
theirimaginaryparts. InDivisionandmultiplication,weusethepolarform.
Giventhecomplexnumbers:
𝑧5 = 𝑟5 𝑒 \„… and 𝑧G = 𝑟G 𝑒 \„† Multiplication:
MATLAB Course - Part I: Introduction to MATLAB
64
Mathematics 𝑧‡ = 𝑧5 𝑧G = 𝑟5 𝑟G 𝑒 \(„… ˆ„† ) Division:
𝑧5 𝑟5 𝑒 \„… 𝑟5 \(„ E„ )
𝑧‡ = =
= 𝑒 … †
𝑧G 𝑟G 𝑒 \„† 𝑟G
MATLABfunctions:
SomeBasicfunctionsforcomplexnumbersinMATLAB:abs,angle,imag,real,conj,
complex,etc. Function
i,j
abs
angle
imag
real
conj
complex
Description
Imaginaryunit.AsthebasicimaginaryunitSQRT(-1),iandjare
usedtoentercomplexnumbers.Forexample,theexpressions
3+2i,3+2*i,3+2j,3+2*jand3+2*sqrt(-1)allhavethesame
value.
abs(x)istheabsolutevalueoftheelementsofx.Whenxis
complex,abs(x)isthecomplexmodulus(magnitude)ofthe
elementsofX.
Phaseangle.angle(z)returnsthephaseangles,inradians
Compleximaginarypart.imag(z)istheimaginarypartofz.
Complexrealpart.real(z)istherealpartofz.
Complexconjugate.conj(x)isthecomplexconjugateofx.
Constructcomplexresultfromrealandimaginaryparts.c=
complex(a,b)returnsthecomplexresultA+Bi
Example
>>z=2+4i
>>z=2+4j
>>z=2+4i
>>abs(z)
>>z=2+4i
>>angle(z)
>>z=2+4i
>>b=imag(z)
>>z=2+4i
>>a=real(z)
>>z=2+4i
>>z_con=conj(z)
>>a=2;
>>b=3;
>>z=complex(a,b)
LookupthesefunctionsintheHelpsysteminMATLAB.
Task25:
Complexnumbers
Giventwocomplexnumbers
𝑐 = 4 + 𝑗3, 𝑑 = 1 − 𝑗
FindtherealandimaginarypartofcanddinMATLAB.
→UseMATLABtofind 𝑐 + 𝑑, 𝑐 − 𝑑, 𝑐𝑑𝑎𝑛𝑑𝑐/𝑑.
UsethedirectmethodsupportedbyMATLABandthespecificcomplexfunctionsabs,angle,
imag,real,conj,complex,etc.togetherwiththeformulasforcomplexnumbersthatare
listedaboveinthetext(asyoudoitwhenyoushouldcalculateitusingpen&paper). →Findalso 𝑟 and 𝜃.Findalsothecomplexconjugate.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
65
Task26:
Mathematics Complexnumbers
Findtherootsoftheequation:
𝑥 G + 4𝑥 + 13
Wecane.g.,usethesolveeqfunctionwecreatedinaprevioustask.Comparetheresults
usingthebuilt-infunctionroots.
Discusstheresults.
Addthesumoftheroots.
[EndofTask]
9.5 Polynomials
Apolynomialisexpressedas:
𝑝 𝑥 = 𝑝5 𝑥 : + 𝑝G 𝑥 :E5 + ⋯ + 𝑝: 𝑥 + 𝑝:ˆ5 where 𝑝5 , 𝑝G , 𝑝‡ , … arethecoefficientsofthepolynomial.
MATLABrepresentspolynomialsasrowarrayscontainingcoefficientsorderedbydescending
powers.
Example:
Giventhepolynomial:
𝑝 𝑥 = −5.45𝑥 Œ + 3.2𝑥 G + 8𝑥 + 5.6
InMATLABwewrite:
>> p=[-5.45 0 3.2 8 5.8]
p =
-5.4500
0
3.2000
8.0000
5.8000
[EndofExample]
MATLABofferslotsoffunctionsonpolynomials,suchasconv,roots,deconv,polyval,
polyint,polyder,polyfit,etc.→LookupthesefunctionsintheHelpsysteminMATLAB.
Task27:
Polynomials
DefinethefollowingpolynomialinMATLAB:
MATLAB Course - Part I: Introduction to MATLAB
66
Mathematics 𝑝 𝑥 = −2.1𝑥 Œ + 2𝑥 ‡ + 5𝑥 + 11
→Findtherootsofthepolynomial(𝑝 𝑥 = 0)(andcheckiftheanswersarecorrect)
→Find 𝑝 𝑥 = 2 Usethepolynomialfunctionslistedabove.
[EndofTask]
Task28:
Polynomials
Giventhefollowingpolynomials:
𝑝5 𝑥 = 1 + 𝑥 − 𝑥 G 𝑝G 𝑥 = 2 + 𝑥 ‡ →Findthepolynomial 𝑝(𝑥) = 𝑝5 (𝑥) ∙ 𝑝G (𝑥) usingMATLABandfindtheroots
→Findtherootsofthepolynomial(𝑝 𝑥 = 0)
→Find 𝑝 𝑥 = 2 →Findthedifferentiation/derivativeof 𝑝G 𝑥 ,i.e., 𝑝G • Usethepolynomialfunctionslistedabove.
[EndofTask]
Task29:
PolynomialFitting
Findthe6.orderPolynomialthatbestfitsthefollowingfunction:
𝑦 = sin(𝑥)
Usethepolynomialfunctionslistedabove.
→Plotboththefunctionandthe6.orderPolynomialtocomparetheresults.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
10 AdditionalTasks
Ifyouhavetimeleftorneedmorepractice,solvethetasksbelow.
Task30:
User-definedfunction
CreateafunctionthatusesPythagorastocalculatethehypotenuseofaright-angledtriangle,
e.g.:
function h = pyt(a,b)
% ..
…
h = …
Pythagorastheoremisasfollows: 𝑐 G = 𝑎G + 𝑏 G Note!Thefunctionshouldhandlethat 𝑎 and 𝑏 couldbevectors.
[EndofTask]
Task31:
MATLABScript
GiventhefamousequationfromAlbertEinstein:
𝐸 = 𝑚𝑐 G Thesunradiates 385𝑥10GŒ 𝐽/𝑠 ofenergy.
→Calculatehowmuchofthemassonthesunisusedtocreatethisenergyperday.
67
68
AdditionalTasks →Howmanyyearswillittaketoconvertallthemassofthesuncompletely?Doweneedto
worryifthesunwillbeusedupinourgenerationorthenext?
Themassofthesunis 2𝑥10‡j 𝑘𝑔
[EndofTask]
Task32:
Cylindersurfacearea
Createafunctionthatfindsthesurfaceareaofacylinderbasedontheheight(h)andthe
radius(r)ofthecylinder.
[EndofTask]
Task33:
CreateadvancedexpressionsinMATLAB
CreatethefollowingexpressioninMATLAB:
ln 𝑎𝑥 G + 𝑏𝑥 + 𝑐 − sin(𝑎𝑥 G + 𝑏𝑥 + 𝑐)
𝑓 𝑥 =
4𝜋𝑥 G + cos(𝑥 − 2)(𝑎𝑥 G + 𝑏𝑥 + 𝑐)
Given 𝑎 = 1, 𝑏 = 3, 𝑐 = 5
→Find 𝑓 9 (Theanswershouldbe 𝑓 9 = 0.0044)
Tip!Youshouldsplittheexpressionsintodifferentparts,suchas:
poly=𝑎𝑥 G + 𝑏𝑥 + 𝑐
num=…
MATLAB Course - Part I: Introduction to MATLAB
69
AdditionalTasks den=….
f=…
Thismakestheexpressionsimplertoreadandunderstand,andyouminimizetheriskof
makinganerrorwhiletypingtheexpressioninMATLAB.
[EndofTask]
Task34:
SolvingEquations
Findthesolution(s)forthegivenequations:
𝑥5 + 2𝑥G = 5
3𝑥5 + 4𝑥G = 6
7𝑥5 + 8𝑥G = 9
[EndofTask]
Task35:
Preallocatingofvariablesandvectorization
HerewewillusepreallocatingofvariablesandvectorizationandcomparewithusingaFor
Loop.
Wewillusethefunctionsticandtoctofindtheexecutiontime.
Wewillcreateasimpleprogramthatcalculates 𝑦 = 𝑐𝑜𝑠(𝑡) fort=1to100000.
CreatethefollowingScript:
% Test 1: Using a For Loop
clear
tic
tmax=100000;
for t=1:tmax
y(t,1)=cos(t);
end
toc
→Whatwastheexecutiontime?
MATLAB Course - Part I: Introduction to MATLAB
70
AdditionalTasks WewillimprovetheScriptbypreallocatingspaceforthevariabley.Createthefollowing
Script:
% Test 2: For Lopp with preallocating
clear
tic
tmax=100000;
y=zeros(tmax,1); % preallocating
for t=1:tmax
y(t,1)=cos(t);
end
toc
→Whatwastheexecutiontime?
WewillimprovetheScriptfurtherbyremovingtheForLoopbyusingvectorizationinstead:
% Test 3: Vectorization
clear
tic
tmax=100000;
t=1:tmax; %vectorization
y=cos(t);
toc
→Whatwastheexecutiontime?
Discusstheresult.
[EndofTask]
Task36:
NestedForLoops
Giventhematrices 𝐴 ∈ 𝑅:=7 and 𝐵 ∈ 𝑅7=Q ,then
𝐶 = 𝐴𝐵 ∈ 𝑅:=Q MATLAB Course - Part I: Introduction to MATLAB
71
AdditionalTasks where
:
𝑎\^ 𝑏^] 𝑐\] =
^R5
InMATLABitiseasytomultiplytwomatrices:
>> A=[0 1;-2 -3]
A =
0
1
-2
-3
>> B=[1 0;3 -2]
B =
1
0
3
>> A*B
ans =
3
-11
-2
-2
6
Butheryouwillcreateyourownfunctionthatmultiplytwomatrices:
function C = matrixmult(A,B)
…
Tip!Youneedtouse3nestedForLoops.
[EndofTask]
MATLAB Course - Part I: Introduction to MATLAB
AppendixA:MATLAB
Functions
ThisAppendixgivesanoverviewofthemostusedfunctionsinthiscourse.
Built-inConstants
MATLABhaveseveralbuilt-inconstants.Someofthemareexplainedhere:
Name
i, j
pi
inf
NaN
Description
Usedforcomplexnumbers,e.g.,z=2+4i
𝜋
∞,Infinity
NotANumber.Ifyou,e.g.,dividebyzero,yougetNaN
BasicFunctions
HerearesomedescriptionsforthemostusedbasicMATLABfunctions.
Function
help
help
<function>
who,whos
clear
size
length
format
disp
plot
clc
rand
max
min
Description
Example
MATLABdisplaysthehelpinformationavailable
>>help
Displayhelpaboutaspecificfunction
>>help plot
wholistsinalphabeticalorderallvariablesinthecurrently
activeworkspace.
Clearvariablesandfunctionsfrommemory.
>>who
>>whos
Sizeofarrays,matrices
Lengthofavector
>>clear
>>clear x
>>x=[1 2 ; 3 4];
>>size(A)
>>x=[1:1:10];
>>length(x)
Setoutputformat
Displaytextorarray
>>A=[1 2;3 4];
>>disp(A)
>>x=[1:1:10];
>>plot(x)
>>y=sin(x);
>>plot(x,y)
>>cls
Thisfunctionisusedtocreateaplot
CleartheCommandwindow
Createsarandomnumber,vectorormatrix
Findthelargestnumberinavector
Findthesmallestnumberinavector
>>rand
>>rand(2,1)
>>x=[1:1:10]
>>max(x)
>>x=[1:1:10]
>>min(x)
72
73
mean
std
AppendixA:MATLABFunctions Averageormeanvalue
>>x=[1:1:10]
>>mean(x)
>>x=[1:1:10]
>>std(x)
Standarddeviation
LinearAlgebra
HerearesomeusefulfunctionsforLinearAlgebrainMATLAB:
Function
rank
det
inv
eig
ones
eye
diag
Description
Findtherankofamatrix.Providesanestimateofthenumber
oflinearlyindependentrowsorcolumnsofamatrixA.
Findthedeterminantofasquarematrix
Findtheinverseofasquarematrix
Findtheeigenvaluesofasquarematrix
Createsanarrayormatrixwithonlyones
Createsanidentitymatrix
Findthediagonalelementsinamatrix
Example
>>A=[1 2; 3 4]
>>rank(A)
>>A=[1 2; 3 4]
>>det(A)
>>A=[1 2; 3 4]
>>inv(A)
>>A=[1 2; 3 4]
>>eig(A)
>>ones(2)
>>ones(2,1)
>>eye(2)
>>A=[1 2; 3 4]
>>diag(A)
Type“helpmatfun”(Matrixfunctions-numericallinearalgebra)intheCommandWindow
formoreinformation,ortype“helpelmat”(Elementarymatricesandmatrixmanipulation).
Youmayalsotype“help<functionname>”forhelpaboutaspecificfunction.
Plotting
Plotsfunctions:Herearesomeusefulfunctionsforcreatingplots:
Function
plot
figure
subplot
grid
axis
title
xlabel
ylabel
Description
Generatesaplot.plot(y)plotsthecolumnsofyagainstthe
indexesofthecolumns.
Createanewfigurewindow
CreatesubplotsinaFigure.subplot(m,n,p)orsubplot(mnp),
breakstheFigurewindowintoanm-by-nmatrixofsmallaxes,
selectsthep-thaxesforthecurrentplot.Theaxesarecounted
alongthetoprowoftheFigurewindow,thenthesecondrow,
etc.
Createsgridlinesinaplot.
“gridon”addsmajorgridlinestothecurrentplot.
“gridoff”removesmajorandminorgridlinesfromthecurrent
plot.
Controlaxisscalingandappearance.“axis([xminxmaxymin
ymax])”setsthelimitsforthex-andy-axisofthecurrentaxes.
Addtitletocurrentplot
title('string')
Addxlabeltocurrentplot
xlabel('string')
Addylabeltocurrentplot
ylabel('string')
Example
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
>>figure
>>figure(1)
>>subplot(2,2,1)
>>grid
>>grid on
>>grid off
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on
>>title('this is a title')
>> xlabel('time')
>> ylabel('temperature')
MATLAB Course - Part I: Introduction to MATLAB
74
legend
hold
AppendixA:MATLABFunctions Createsalegendinthecorner(orataspecifiedposition)ofthe
plot
Freezesthecurrentplot,sothatadditionalplotscanbe
overlaid
>> legend('temperature')
>>hold on
>>hold off
Type“helpgraphics”intheCommandWindowformoreinformation,ortype“help
<functionname>”forhelpaboutaspecificfunction.
Operators:
YoumayusethefollowingoperatorsinMATLAB:
MathematicalOperator
<
≤
>
≥
=
≠
Description
LessThan
LessThanorEqualTo
GreaterThan
GreaterThanorEqualTo
EqualTo
NotEqualTo
MATLABOperator
<
<=
>
>=
==
~=
LogicalOperators
YoumayusethefollowinglogicaloperatorsinMATLAB:
LogicalOperator
AND
OR
MATLABOperator
&
|
ComplexNumbers
Functionsusedtocreateormanipulatecomplexnumbers.
Function
i,j
abs
angle
imag
real
conj
complex
Description
Imaginaryunit.AsthebasicimaginaryunitSQRT(-1),iandjare
usedtoentercomplexnumbers.Forexample,theexpressions
3+2i,3+2*i,3+2j,3+2*jand3+2*sqrt(-1)allhavethesame
value.
abs(x)istheabsolutevalueoftheelementsofx.Whenxis
complex,abs(x)isthecomplexmodulus(magnitude)ofthe
elementsofX.
Phaseangle.angle(z)returnsthephaseangles,inradians
Compleximaginarypart.imag(z)istheimaginarypartofz.
Complexrealpart.real(z)istherealpartofz.
Complexconjugate.conj(x)isthecomplexconjugateofx.
Constructcomplexresultfromrealandimaginaryparts.c=
complex(a,b)returnsthecomplexresultA+Bi
Example
>>z=2+4i
>>z=2+4j
>>z=2+4i
>>abs(z)
>>z=2+4i
>>angle(z)
>>z=2+4i
>>b=imag(z)
>>z=2+4i
>>a=real(z)
>>z=2+4i
>>z_con=conj(z)
>>a=2;
>>b=3;
>>z=complex(a,b)
MATLAB Course - Part I: Introduction to MATLAB
Hans-PetterHalvorsen,M.Sc.
E-mail:hans.p.halvorsen@hit.no
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no 
Download