37
University College of Southeast Norway http://home.hit.no/~hansha Introduction to MATLAB Hans-Petter Halvorsen, 2016.11.01

University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

  • Upload
    buidang

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

Page 1: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

UniversityCollegeofSoutheastNorway

http://home.hit.no/~hansha

IntroductiontoMATLABHans-PetterHalvorsen,2016.11.01

Page 2: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

PrefaceMATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment.ThisdocumentexplainsthebasicconceptsinMATLAB.

MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedformatrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.

MATLABofferslotsofadditionalToolboxesfordifferentareassuchasControlDesign,ImageProcessing,DigitalSignalProcessing,etc.

FormoreinformationaboutMATLAB,seemyBlog:http://home.hit.no/~hansha

Page 3: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

iii

TableofContentsPreface......................................................................................................................................2

TableofContents.....................................................................................................................iii

1 Introduction......................................................................................................................1

1.1 Help.............................................................................................................................2

2 StartusingMATLAB...........................................................................................................4

2.1 TheMATLABEnvironment..........................................................................................4

2.1.1 CommandWindow..............................................................................................4

2.1.2 CommandHistory................................................................................................5

2.2 Variables.....................................................................................................................6

2.2.1 Workspace...........................................................................................................6

2.2.2 CurrentDirectory.................................................................................................7

2.3 Usefulcommands.......................................................................................................8

3 MatricesandVectors........................................................................................................9

3.1 Usefulcommands.....................................................................................................11

4 Scriptsandfunctions–MFiles........................................................................................12

4.1 Scripts.......................................................................................................................12

4.2 Functions..................................................................................................................13

5 FlowControl....................................................................................................................15

5.1 If-elseStatement......................................................................................................15

5.2 SwitchandCaseStatement......................................................................................15

5.3 Forloop.....................................................................................................................16

5.4 Whileloop.................................................................................................................16

Page 4: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

iv TableofContents

6 Plotting............................................................................................................................17

7 LinearAlgebra.................................................................................................................19

7.1 Vectors......................................................................................................................19

7.2 Matrices....................................................................................................................20

7.2.1 Transpose..........................................................................................................20

7.2.2 Diagonal.............................................................................................................20

7.2.3 Triangular..........................................................................................................21

7.2.4 MatrixMultiplication.........................................................................................21

7.2.5 MatrixAddition.................................................................................................22

7.2.6 Determinant......................................................................................................22

7.2.7 InverseMatrices................................................................................................23

7.3 Eigenvalues...............................................................................................................24

7.4 SolvingLinearEquations...........................................................................................25

7.5 LUfactorization.........................................................................................................26

7.6 TheSingularValueDecomposition(SVD).................................................................27

7.7 Commands................................................................................................................27

8 Toolboxes........................................................................................................................28

9 WhatsNext?....................................................................................................................29

QuickReference......................................................................................................................31

9.1 General.....................................................................................................................31

9.2 Matrices....................................................................................................................31

9.3 LinearAlgebra...........................................................................................................31

Page 5: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

1

1 IntroductionMATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment,e.g.,

• Mathandcomputation• Algorithmdevelopment• Dataacquisition• Modeling,simulation,andprototyping• Dataanalysis,exploration,andvisualization• Scientificandengineeringgraphics• Applicationdevelopment,includinggraphicaluserinterfacebuilding

MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.MATLABisinuseworld-widebyresearchersanduniversities.

Formoreinformation,seewww.mathworks.com

BelowweseetheMATLABEnvironment:

MATLABhasthefollowingwindows:

• CommandWindow

Page 6: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

2 Introduction

Tutorial:IntroductiontoMATLAB

• CommandHistory• Workspace• CurrentDirectory

TheCommandwindowisthemainwindow.UsetheCommandWindowtoentervariablesandtorunfunctionsandM-filesscripts(moreaboutm-fileslater).

Watchthefollowing“GettingStartedwithMATLAB”video:

http://www.mathworks.com/demos/matlab/getting-started-with-matlab-video-tutorial.html

1.1 HelpMATLABhasacomprehensiveHelpsystem.

Youmayalsotypehelpinyourcommandwindow

>>help

Ormorespecific,e.g.,

>>help plot

Page 7: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

3 Introduction

Tutorial:IntroductiontoMATLAB

IadviseyoutotestalltheexamplesinthistextinMATLABinordertogetfamiliarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelikethis:

>> …

Page 8: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

4

2 StartusingMATLABThischapterexplainsthebasicconceptsinMATLAB.

Thetopicsareasfollows:

• TheMATLABEnvironmento CommandWindowo CommandHistoryo Workspaceo CurrentDirectory

• Variables

2.1 TheMATLABEnvironment

2.1.1 CommandWindow

TheCommandwindowisthemainwindow.UsetheCommandWindowtoentervariablesandtorunfunctionsandM-filesscripts(moreaboutm-fileslater).

YoutypeallyourcommandsafterthecommandPrompt“>>”,e.g.,definingthefollowingmatrix

Page 9: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

5 StartusingMATLAB

Tutorial:IntroductiontoMATLAB

𝐴 = 1 20 3

TheMATLABsyntaxisasfollows:

>> A = [1 2;0 3]

Or

>> A = [1,2;0,3]

Ifyou,foranexample,wanttofindtheanswerto

𝑎 + 𝑏,𝑤ℎ𝑒𝑟𝑒𝑎 = 4, 𝑏 = 3

>>a=4 >>b=3 >>a+b

MATLABthenresponds:

ans = 7

2.1.2 CommandHistory

StatementsyouenterintheCommandWindowareloggedintheCommandHistory.FromtheCommandHistory,youcanviewandsearchforpreviouslyrunstatements,aswellascopyandexecuteselectedstatements.YoucanalsocreateanM-filefromselectedstatements.

Page 10: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

6 StartusingMATLAB

Tutorial:IntroductiontoMATLAB

2.2 VariablesVariablesaredefinedwiththeassignmentoperator,“=”.MATLABisdynamicallytyped,meaningthatvariablescanbeassignedwithoutdeclaringtheirtype,andthattheirtypecanchange.Valuescancomefromconstants,fromcomputationinvolvingvaluesofothervariables,orfromtheoutputofafunction.Forexample:

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

Unlikemanyotherlanguages,wherethesemicolonisusedtoterminatecommands,inMATLABthesemicolonservestosuppresstheoutputofthelinethatitconcludes.

>> a=5 a = 5 >> a=6; >>

Asyousee,whenyoutypeasemicolon(;)afterthecommand,MATLABwillnotrespond.

2.2.1 Workspace

TheWorkspacewindowlistallyourvariablesusedaslongyouhaveMATLABopened.

Page 11: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

7 StartusingMATLAB

Tutorial:IntroductiontoMATLAB

Youcouldalsousethefollowingcommand

>>who

Thiscommandlistallthecommandsused

or

>>whos

Thiscommandlistsallthecommandwiththecurrentvalues,dimensions,etc.

Thecommandclear,willclearallthevariables.

>>clear

2.2.2 CurrentDirectory

TheCurrentDirectorywindowlistalmfiles,etc.

Page 12: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

8 StartusingMATLAB

Tutorial:IntroductiontoMATLAB

2.3 UsefulcommandsHerearesomeusefulcommands:

Command Description

help Help

help x Givesyouhelponsubject“x”

who, whos Getlistofvariables

clear ClearsallvariablesintheWorkspace

clear x Clearsthevariablex

what ListallmfilesintheWorkingFolder

Page 13: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

9

3 MatricesandVectorsThischapterexplainsthebasicconceptsofusingvectorsandmatricesinMATLAB.

Topics:

• MatricesandVectorssyntax• Matricesfunctions

MATLABisa"MatrixLaboratory",andassuchitprovidesmanyconvenientwaysforcreatingvectors,matrices,andmulti-dimensionalarrays.IntheMATLAB,avectorreferstoaonedimensional(1×NorN×1)matrix,commonlyreferredtoasanarrayinotherprogramminglanguages.Amatrixgenerallyreferstoa2-dimensionalarray,i.e.anm×narraywheremandnaregreaterthanorequalto1.Arrayswithmorethantwodimensionsarereferredtoasmultidimensionalarrays.

MATLABprovidesasimplewaytodefinesimplearraysusingthesyntax:“init:increment:terminator”.Forinstance:

>> array = 1:2:9 array = 1 3 5 7 9

definesavariablenamedarray(orassignsanewvaluetoanexistingvariablewiththenamearray)whichisanarrayconsistingofthevalues1,3,5,7,and9.Thatis,thearraystartsat1(theinitvalue),incrementswitheachstepfromthepreviousvalueby2(theincrementvalue),andstopsonceitreaches(ortoavoidexceeding)9(theterminatorvalue).

Theincrementvaluecanactuallybeleftoutofthissyntax(alongwithoneofthecolons),touseadefaultvalueof1.

>> ari = 1:5 ari = 1 2 3 4 5

assignstothevariablenamedarianarraywiththevalues1,2,3,4,and5,sincethedefaultvalueof1isusedastheincrementer.

Notethattheindexingisone-based,whichistheusualconventionformatricesinmathematics.Thisisatypicalforprogramminglanguages,whosearraysmoreoftenstartwithzero.

Page 14: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

10 MatricesandVectors

Tutorial:IntroductiontoMATLAB

Matricescanbedefinedbyseparatingtheelementsofarowwithblankspaceorcommaandusingasemicolontoterminateeachrow.Thelistofelementsshouldbesurroundedbysquarebrackets:[].Parentheses:()areusedtoaccesselementsandsubarrays(theyarealsousedtodenoteafunctionargumentlist).

>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> A(2,3) ans = 11

Setsofindicescanbespecifiedbyexpressionssuchas"2:4",whichevaluatesto[2,3,4].Forexample,asubmatrixtakenfromrows2through4andcolumns3through4canbewrittenas:

>> A(2:4,3:4) ans = 11 8 7 12 14 1

Asquareidentitymatrixofsizencanbegeneratedusingthefunctioneye,andmatricesofanysizewithzerosoronescanbegeneratedwiththefunctionszerosandones,respectively.

>> eye(3) ans = 1 0 0 0 1 0 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1

MostMATLABfunctionscanacceptmatricesandwillapplythemselvestoeachelement.Forexample,mod(2*J,n)willmultiplyeveryelementin"J"by2,andthenreduceeachelementmodulo"n".MATLABdoesincludestandard"for"and"while"loops,butusingMATLAB'svectorizednotationoftenproducescodethatiseasiertoreadandfastertoexecute.Thiscode,excerptedfromthefunctionmagic.m,createsamagicsquareMforoddvaluesofn

Page 15: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

11 MatricesandVectors

Tutorial:IntroductiontoMATLAB

(thebuilt-inMATLABfunctionmeshgridisusedheretogeneratesquarematricesIandJcontaining1:n).

[J,I] = meshgrid(1:n); A = mod(I+J-(n+3)/2,n); B = mod(I+2*J-2,n); M = n*A + B + 1;

3.1 UsefulcommandsHerearesomeusefulcommands:

Command Description

eye(x), eye(x,y) Identitymatrixoforderx

ones(x), ones(x,y) Amatrixwithonlyones

zeros(x), zeros(x,y) Amatrixwithonlyzeros

diag([x y z]) Diagonalmatrix

size(A) DimensionofmatrixA

A’ InverseofmatrixA

Page 16: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

12

4 Scriptsandfunctions–MFiles

M-filesaretextfilescontainingMATLABcode.UsetheMATLABEditororanothertexteditortocreateafilecontainingthesamestatementsyouwouldtypeattheMATLABcommandline.Savethefileunderanamethatendsin“.m”.

4.1 ScriptsCreateanewm-filefromtheFile→NewmenuortheNewbuttonontheToolbar.

Thebuilt-inEditorforcreatingandmodifyingm-files:

Page 17: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

13 Scriptsandfunctions–MFiles

Tutorial:IntroductiontoMATLAB

Runningam-fileintheCommandwindow:

4.2 FunctionsYoumaycreateyourownfunctionsandsavethemasam-file.

Example:

Createafunctioncalled“linsolution”whichsolve 𝐴𝑥 = 𝑏 → 𝑥 = 𝐴34𝑏

Belowweseehowthem-fileforthisfunctionlookslike:

Page 18: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

14 Scriptsandfunctions–MFiles

Tutorial:IntroductiontoMATLAB

YoumaydefineAandbintheCommandwindowandtheusethefunctiononordertofindx:

>> 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“%”beforeeachline.

FromtheCommandwindowyoucanthentype“help <function name>”inordertoreadthisinformation:

>> help linsolution Solves the problem Ax=b using x=inv(A)*b Created By Hans-Petter Halvorsen

Page 19: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

15

5 FlowControlThischapterexplainsthebasicconceptsofflowcontrolinMATLAB.

Thetopicsareasfollows:

• If-elsestatement• Switchandcasestatement• Forloop• Whileloop

5.1 If-elseStatementTheifstatementevaluatesalogicalexpressionandexecutesagroupofstatementswhentheexpressionistrue.Theoptionalelseifandelsekeywordsprovidefortheexecutionofalternategroupsofstatements.Anendkeyword,whichmatchestheif,terminatesthelastgroupofstatements.Thegroupsofstatementsaredelineatedbythefourkeywords—nobracesorbracketsareinvolved.

Example:

n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end

5.2 SwitchandCaseStatementTheswitchstatementexecutesgroupsofstatementsbasedonthevalueofavariableorexpression.Thekeywordscaseandotherwisedelineatethegroups.Onlythefirstmatchingcaseisexecuted.Theremustalwaysbeanendtomatchtheswitch.

Example:

n=2 switch(n)

Page 20: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

16 FlowControl

Tutorial:IntroductiontoMATLAB

case 1 M = eye(n) case 2 M = zeros(n) case 3 M = ones(n) end

5.3 ForloopTheforlooprepeatsagroupofstatementsafixed,predeterminednumberoftimes.Amatchingenddelineatesthestatements.

Example:

m=5 for n = 1:m r(n) = rank(magic(n)); end r

5.4 WhileloopThewhilelooprepeatsagroupofstatementsanindefinitenumberoftimesundercontrolofalogicalcondition.Amatchingenddelineatesthestatements.

Example:

m=5; while m > 1 m = m - 1; zeros(m) end

Page 21: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

17

6 PlottingThischapterexplainsthebasicconceptsofcreatingplotsinMATLAB.

Topics:

• BasicPlotcommands

Functionplotcanbeusedtoproduceagraphfromtwovectorsxandy.Thecode:

x = 0:pi/100:2*pi; y = sin(x); plot(x,y)

producesthefollowingfigureofthesinefunction:

Three-dimensionalgraphicscanbeproducedusingthefunctionssurf,plot3ormesh.

[X,Y] = meshgrid(-10:0.25:10,-10:0.25:10); f = sinc(sqrt((X/pi).^2+(Y/pi).^2)); mesh(X,Y,f); axis([-10 10 -10 10 -0.3 1]) xlabel('{\bfx}') ylabel('{\bfy}') zlabel('{\bfsinc} ({\bfR})') hidden off

Page 22: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

18 Plotting

Tutorial:IntroductiontoMATLAB

Thiscodeproducesthefollowing3Dplot:

Page 23: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

19

7 LinearAlgebraLinearalgebraisabranchofmathematicsconcernedwiththestudyofmatrices,vectors,vectorspaces(alsocalledlinearspaces),linearmaps(alsocalledlineartransformations),andsystemsoflinearequations.

MATLABarewellsuitedforLinearAlgebra.

7.1 VectorsGivenavectorx

𝑥 =

𝑥4𝑥5⋮𝑥7

∈ 𝑅7

Example:

𝑥 =123

>> x=[1; 2; 3] x = 1 2 3

TheTransposeofvectorx:

𝑥: = 𝑥4 𝑥5 ⋯ 𝑥7 ∈ 𝑅4<7

>> x' ans = 1 2 3

TheLengthofvectorx:

𝑥 = 𝑥:𝑥 = 𝑥45 + 𝑥55 + ⋯+ 𝑥75

Orthogonality:

Page 24: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

20 LinearAlgebra

Tutorial:IntroductiontoMATLAB

𝑥:𝑦 = 0

7.2 MatricesGivenamatrixA:

𝐴 =𝑎44 ⋯ 𝑎4>⋮ ⋱ ⋮𝑎74 ⋯ 𝑎7>

∈ 𝑅7<>

Example:

𝐴 = 0 1−2 −3

>> A=[0 1;-2 -3] A = 0 1 -2 -3

7.2.1 Transpose

TheTransposeofmatrixA:

𝐴: =𝑎44 ⋯ 𝑎74⋮ ⋱ ⋮

𝑎4> ⋯ 𝑎7>∈ 𝑅><7

Example:

𝐴: = 0 1−2 −3

:= 0 −2

1 −3

>> A' ans = 0 -2 1 -3

7.2.2 Diagonal

TheDiagonalelementsofmatrixAisthevector

𝑑𝑖𝑎𝑔(𝐴) =

𝑎44𝑎55⋮𝑎FF

∈ 𝑅FGHIJ(<,>)

Page 25: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

21 LinearAlgebra

Tutorial:IntroductiontoMATLAB

Example:

>> diag(A) ans = 0 -3

TheDiagonalmatrixΛisgivenby:

Λ =

𝜆4 0 ⋯ 00 𝜆5 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 𝜆7

∈ 𝑅7<7

GiventheIdentitymatrixI:

𝐼 =

1 0 ⋯ 00 1 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 1

∈ 𝑅7<>

Example:

>> eye(3) ans = 1 0 0 0 1 0 0 0 1

7.2.3 Triangular

LowerTriangularmatrixL:

𝐿 =. 0 0⋮ ⋱ 0. ⋯ .

UpperTriangularmatrixU:

𝑈 =. ⋯ .0 ⋱ ⋮0 0 .

7.2.4 MatrixMultiplication

Giventhematrices 𝐴 ∈ 𝑅7<> and 𝐵 ∈ 𝑅><F,then

𝐶 = 𝐴𝐵 ∈ 𝑅7<F

Page 26: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

22 LinearAlgebra

Tutorial:IntroductiontoMATLAB

where

𝑐TU = 𝑎TV𝑏VU

7

VG4

Example:

>> A=[0 1;-2 -3] A = 0 1 -2 -3 >> B=[1 0;3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6

Note!

𝐴𝐵 ≠ 𝐵𝐴

𝐴 𝐵𝐶 = 𝐴𝐵 𝐶

𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶

𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵

7.2.5 MatrixAddition

Giventhematrices 𝐴 ∈ 𝑅7<> and 𝐵 ∈ 𝑅7<>,then

𝐶 = 𝐴 + 𝐵 ∈ 𝑅7<>

Example:

>> A=[0 1;-2 -3] >> B=[1 0;3 -2] >> A+B ans = 1 1 1 -5

7.2.6 Determinant

Givenamatrix 𝐴 ∈ 𝑅7<7,thentheDeterminantisgiven:

Page 27: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

23 LinearAlgebra

Tutorial:IntroductiontoMATLAB

det 𝐴 = 𝐴

Givena2x2matrix

𝐴 =𝑎44 𝑎45𝑎54 𝑎55 ∈ 𝑅5<5

Then

det 𝐴 = 𝐴 = 𝑎44𝑎55 − 𝑎54𝑎45

Example:

A = 0 1 -2 -3 >> det(A) ans = 2

Noticethat

det 𝐴𝐵 = det 𝐴 det 𝐵

and

det 𝐴: = det(𝐴)

Example:

>> det(A*B) ans = -4 >> det(A)*det(B) ans = -4 >> det(A') ans = 2 >> det(A) ans = 2

7.2.7 InverseMatrices

Page 28: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

24 LinearAlgebra

Tutorial:IntroductiontoMATLAB

Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅7<7 isdefinedby:

𝐴34

if

𝐴𝐴34 = 𝐴34𝐴 = 𝐼

Fora2x2matrixwehave:

𝐴 =𝑎44 𝑎45𝑎54 𝑎55 ∈ 𝑅5<5

Theinverse 𝐴34 isgivenby

𝐴34 =1

det(𝐴)𝑎55 −𝑎45−𝑎54 𝑎44 ∈ 𝑅5<5

Example:

A = 0 1 -2 -3 >> inv(A) ans = -1.5000 -0.5000 1.0000 0

Noticethat:

𝐴𝐴34 = 𝐴34𝐴 = 𝐼

→ProvethisinMATLAB

7.3 EigenvaluesGiven 𝐴 ∈ 𝑅7<7,thentheEigenvaluesisdefinedas:

det 𝜆𝐼 − 𝐴 = 0

Example:

A = 0 1 -2 -3 >> eig(A) ans = -1 -2

Page 29: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

25 LinearAlgebra

Tutorial:IntroductiontoMATLAB

7.4 SolvingLinearEquationsGiventhelinearequation

𝐴𝑥 = 𝑏

withthesolution:

𝑥 = 𝐴34𝑏

(AssumingthattheinverseofAexists)

Example:

Theequations

𝑥4 + 2𝑥5 = 53𝑥4 + 4𝑥5 = 6

maybewritten

𝐴𝑥 = 𝑏

1 23 4

𝑥4𝑥5 = 5

6

where

𝐴 = 1 23 4

𝑥 =𝑥4𝑥5

𝑏 = 56

Thesolutionis:

A = 1 2 3 4 >> b=[5;6] b = 5 6 >> x=inv(A)*b x = -4.0000 4.5000

InMATLAByoucouldalsowrite“x=A\b”,whichshouldgivethesameanswer.ThissyntaxcanalsobeusedwhentheinverseofAdon’texists.

Page 30: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

26 LinearAlgebra

Tutorial:IntroductiontoMATLAB

Example:

>> A=[1 2;3 4;7 8] >> x=inv(A)*b ??? Error using ==> inv Matrix must be square. >> x=A\b x = -3.5000 4.1786

7.5 LUfactorizationLUfactorizationof 𝐴 ∈ 𝑅7<> isgivenby

𝐴 = 𝐿𝑈

where

Lisalowertriangularmatrix

Uisauppertriangularmatrix

TheMATLABsyntaxis[L,U]=lu(A)

Example:

>> A=[1 2;3 4] >> [L,U]=lu(A) L = 0.3333 1.0000 1.0000 0 U = 3.0000 4.0000 0 0.6667

OrsometimesLUfactorizationof 𝐴 ∈ 𝑅7<> isgivenby

𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈

where

Disadiagonalmatrix

TheMATLABsyntaxis[L,U,P]=lu(A)

Example:

>> A=[1 2;3 4] A = 1 2 3 4

Page 31: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

27 LinearAlgebra

Tutorial:IntroductiontoMATLAB

>> [L,U,P]=lu(A) L = 1.0000 0 0.3333 1.0000 U = 3.0000 4.0000 0 0.6667 P = 0 1 1 0

7.6 TheSingularValueDecomposition(SVD)TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅7<> isgivenby

𝐴 = 𝑈𝑆𝑉:

where

Uisaorthogonalmatrix

Visaorthogonalmatrix

Sisadiagonalsingularmatrix

Example:

>> A=[1 2;3 4]; >> [U,S,V] = svd(A) U = -0.4046 -0.9145 -0.9145 0.4046 S = 5.4650 0 0 0.3660 V = -0.5760 0.8174 -0.8174 -0.5760

7.7 Commands

Command Description

[L,U]=lu(A)

[L,U,P]=lu(A)LUFactorization

[U,S,V] = svd(A) SingularValueDecomposition(SVD)

Page 32: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

28

8 ToolboxesToolboxesarespecializedcollectionsofM-filesbuiltforsolvingparticularclassesofproblems,e.g.,

• ControlSystemToolbox• SignalProcessingToolbox• StatisticsToolbox• SystemidentificationToolbox• etc.

Page 33: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

29

9 WhatsNext?TherearelotsofusefulresourcestodigintoifyouwanttolearnmoreaboutMATLAB.

TypedemointheCommandwindowinMATLAB

>>demo

Inthe“GettingStatedwithDemos”intheMATLAHelpsystemyougetaccesstotonsofDemosinformofM-files,Videos,etc.

FormoreinformationaboutMATLAB,seewww.mathworks.com

AttheMathWorkshomepagetherearelotsofDocumentation,Examples,Videos,TipsandTricks,etc.

AnotherresourceistheMATLABdocumentation(maybedownloadedaspdffilesfromwww.mathworks.com),suchas:

• MATLABDesktopToolsandDevelopmentEnvironment• MATLABGettingStartedGuide• MATLABFunctionReference

Page 34: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

30 LinearAlgebra

Tutorial:IntroductiontoMATLAB

• MATLABMathematics• MATLABGraphics• Etc.

Page 35: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

31

QuickReference

9.1 General

Command Description

help Help

help x Givesyouhelponsubject“x”

who, whos Getlistofvariables

clear ClearsallvariablesintheWorkspace

clear x Clearsthevariablex

what ListallmfilesintheWorkingFolder

9.2 Matrices

Command Description

eye(x), eye(x,y) Identitymatrixoforderx

ones(x), ones(x,y) Amatrixwithonlyones

zeros(x), zeros(x,y) Amatrixwithonlyzeros

diag([x y z]) Diagonalmatrix

size(A) DimensionofmatrixA

A’ InverseofmatrixA

9.3 LinearAlgebra

Command Description

Page 36: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

QuickReference

Tutorial:IntroductiontoMATLAB

[L,U]=lu(A)

[L,U,P]=lu(A)LUFactorization

[U,S,V] = svd(A) SingularValueDecomposition(SVD)

Page 37: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training...2 Introduction Tutorial: Introduction to MATLAB • Command History • Workspace • Current

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no