UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
LinearAlgebrainLabVIEWHans-PetterHalvorsen,2016-10-31
PrefaceThisdocumentexplainsthebasicconceptsofLinearAlgebraandhowyoumayuseLabVIEWforcalculationoftheseproblems.
YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“AnIntroductiontoLabVIEW”training.Thisdocumentisavailablefordownloadathttp://home.hit.no/~hansha/.
FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
iii
TableofContentsPreface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1 IntroductiontoLabVIEW...................................................................................................1
1.1 Dataflowprogramming...............................................................................................1
1.2 Graphicalprogramming..............................................................................................2
1.3 Benefits.......................................................................................................................2
1.4 LabVIEWMathScriptRTModule................................................................................3
2 IntroductiontoLinearAlgebra..........................................................................................4
2.1.1 Transpose............................................................................................................4
2.1.2 Diagonal...............................................................................................................4
2.1.3 MatrixMultiplication...........................................................................................5
2.1.4 MatrixAddition...................................................................................................5
2.1.5 Determinant........................................................................................................5
2.1.6 InverseMatrices..................................................................................................5
2.2 Eigenvalues.................................................................................................................6
2.3 SolvingLinearEquations.............................................................................................6
2.4 LUfactorization...........................................................................................................7
2.5 TheSingularValueDecomposition(SVD)...................................................................7
3 LinearAlgebraPaletteinLabVIEW....................................................................................8
3.1 Vectors........................................................................................................................9
3.2 Matrices....................................................................................................................10
3.2.1 Transpose..........................................................................................................10
iv TableofContents
Tutorial:LinearAlgebrainLabVIEW
3.2.2 Diagonal.............................................................................................................11
3.2.3 MatrixMultiplication.........................................................................................12
3.2.4 MatrixAddition.................................................................................................13
3.2.5 Determinant......................................................................................................14
3.2.6 InverseMatrices................................................................................................15
3.3 Eigenvalues...............................................................................................................16
3.4 SolvingLinearEquations...........................................................................................16
3.5 LUfactorization.........................................................................................................17
3.6 TheSingularValueDecomposition(SVD).................................................................19
4 LabVIEWMathScriptRTModule.....................................................................................20
5 LabVIEWMathScript.......................................................................................................21
5.1 Help...........................................................................................................................22
5.2 Examples...................................................................................................................22
5.3 Usefulcommands.....................................................................................................25
5.4 FlowControl.............................................................................................................25
5.4.1 If-elseStatement...............................................................................................25
5.4.2 SwitchandCaseStatement...............................................................................26
5.4.3 Forloop.............................................................................................................26
5.4.4 Whileloop.........................................................................................................26
5.5 Plotting.....................................................................................................................28
6 LinearAlgebraExamplesusingMathScript.....................................................................30
6.1 Vectors......................................................................................................................30
6.2 Matrices....................................................................................................................31
6.2.1 Transpose..........................................................................................................31
6.2.2 Diagonal.............................................................................................................32
6.2.3 Triangular..........................................................................................................32
v TableofContents
Tutorial:LinearAlgebrainLabVIEW
6.2.4 MatrixMultiplication.........................................................................................33
6.2.5 MatrixAddition.................................................................................................33
6.2.6 Determinant......................................................................................................34
6.2.7 InverseMatrices................................................................................................35
6.3 Eigenvalues...............................................................................................................36
6.4 SolvingLinearEquations...........................................................................................36
6.5 LUfactorization.........................................................................................................37
6.6 TheSingularValueDecomposition(SVD).................................................................38
6.7 Commands................................................................................................................39
7 MathScriptNode.............................................................................................................40
7.1 TransferringMathScriptNodesbetweenComputers...............................................42
7.2 Examples...................................................................................................................42
7.3 Exercises...................................................................................................................46
8 WhatsNext?....................................................................................................................47
8.1 MyBlog.....................................................................................................................47
8.2 Training.....................................................................................................................47
8.3 MathScriptFunctions................................................................................................47
QuickReference......................................................................................................................49
1
1 IntroductiontoLabVIEWLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofUNIX,Linux,andMacOSX.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
ThispaperispartofaserieswithLabVIEWpapers:
• IntroductiontoLabVIEW• LinearAlgebrainLabVIEW• DataAcquisitionandInstrumentControlinLabVIEW• ControlDesignandSimulationinLabVIEW• SignalProcessinginLabVIEW• DataloggingandSupervisoryControlinLabVIEW• SystemidentificationinLabVIEW• ModelbasedControlinLabVIEW• AdvancedTopicsinLabVIEW
Eachpapermaybeusedindependentlyofeachother.
1.1 DataflowprogrammingTheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.
2 IntroductiontoLabVIEW
Tutorial:LinearAlgebrainLabVIEW
1.2 GraphicalprogrammingLabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinestheinputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragginganddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthedocumentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthattheprogrammerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthetopologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystemsofferthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreatedistributedapplications,whichcommunicatebyaclient/serverscheme,andarethereforeeasiertoimplementduetotheinherentlyparallelnatureofG-code.
1.3 BenefitsOnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportforaccessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypesofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresentthemselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacestocommunicatewithhardwaredevices.Theprovideddriverinterfacessaveprogramdevelopmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeoplewithlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareducedtimeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardwaredrivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlyafewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)functions,providesplatformindependenthardwareaccesstonumerousdataacquisition
3 IntroductiontoLabVIEW
Tutorial:LinearAlgebrainLabVIEW
andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,MacOSXandLinuxplatforms.
FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
1.4 LabVIEWMathScriptRTModuleTheLabVIEWMathScriptRTModuleisanadd-onmoduletoLabVIEW.WithLabVIEWMathScriptRTModuleyoucan:
• Deployyourcustom.mfilestoNIreal-timehardware• ReusemanyofyourscriptscreatedwithTheMathWorks,Inc.MATLAB®softwareand
others• Developyour.mfileswithaninteractivecommand-lineinterface• EmbedyourscriptsintoyourLabVIEWapplicationsusingtheMathScriptNode
4
2 IntroductiontoLinearAlgebra
GivenamatrixA:
𝐴 =𝑎$$ ⋯ 𝑎$&⋮ ⋱ ⋮𝑎)$ ⋯ 𝑎)&
∈ 𝑅)-&
Example:
𝐴 = 0 1−2 −3
2.1.1 Transpose
TheTransposeofmatrixA:
𝐴3 = 0 −21 −3
2.1.2 Diagonal
TheDiagonalelementsofmatrixAisthevector
𝑑𝑖𝑎𝑔(𝐴) =
𝑎$$𝑎99⋮𝑎::
∈ 𝑅:;<=>(-,&)
TheDiagonalmatrixΛisgivenby:
Λ =
𝜆$ 0 ⋯ 00 𝜆9 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 𝜆)
∈ 𝑅)-)
GiventheIdentitymatrixI:
5 IntroductiontoLinearAlgebra
Tutorial:LinearAlgebrainLabVIEW
𝐼 =
1 0 ⋯ 00 1 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 1
∈ 𝑅)-&
2.1.3 MatrixMultiplication
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-:,then
𝐶 = 𝐴𝐵 ∈ 𝑅)-:
2.1.4 MatrixAddition
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅)-&,then
𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-&
2.1.5 Determinant
Givenamatrix 𝐴 ∈ 𝑅)-),thentheDeterminantisgiven:
det 𝐴 = 𝐴
Givena2x2matrix
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Then
det 𝐴 = 𝐴 = 𝑎$$𝑎99 − 𝑎9$𝑎$9
Noticethat
det 𝐴𝐵 = det 𝐴 det 𝐵
and
det 𝐴3 = det(𝐴)
2.1.6 InverseMatrices
Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅)-) isdefinedby:
𝐴I$
6 IntroductiontoLinearAlgebra
Tutorial:LinearAlgebrainLabVIEW
if
𝐴𝐴I$ = 𝐴I$𝐴 = 𝐼
Fora2x2matrixwehave:
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Theinverse 𝐴I$ isgivenby
𝐴I$ =1
det(𝐴)𝑎99 −𝑎$9−𝑎9$ 𝑎$$ ∈ 𝑅9-9
2.2 EigenvaluesGiven 𝐴 ∈ 𝑅)-),thentheEigenvaluesisdefinedas:
det 𝜆𝐼 − 𝐴 = 0
2.3 SolvingLinearEquationsGiventhelinearequation
𝐴𝑥 = 𝑏
withthesolution:
𝑥 = 𝐴I$𝑏
(AssumingthattheinverseofAexists)
Example:
Theequations
𝑥$ + 2𝑥9 = 53𝑥$ + 4𝑥9 = 6
maybewritten
𝐴𝑥 = 𝑏
1 23 4
𝑥$𝑥9 = 5
6
where
7 IntroductiontoLinearAlgebra
Tutorial:LinearAlgebrainLabVIEW
𝐴 = 1 23 4
𝑥 =𝑥$𝑥9
𝑏 = 56
2.4 LUfactorizationLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈
where
Lisalowertriangularmatrix
Uisauppertriangularmatrix
OrsometimesLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈
where
Disadiagonalmatrix
2.5 TheSingularValueDecomposition(SVD)TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝑈𝑆𝑉3
where
Uisaorthogonalmatrix
Visaorthogonalmatrix
Sisadiagonalsingularmatrix
8
3 LinearAlgebraPaletteinLabVIEW
ForanIntroductiontoLabVIEW,seethetraining:“AnIntroductiontoLabVIEW”.YoumaydownloaditfrommyBlog:http://home.hit.no/~hansha/
UsetheLinearAlgebraPaletteinordertosolveLinearAlgebraproblemswiththeuseofGraphicalprogramming.
IntheMatrixSubPalettewehavethefollowingfunctions:
9 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
LabVIEWusesarraystorepresentsvectorsandmatrices.Avectorisrepresentedasaonedimensionalarray,whileamatrixisrepresentedasatwodimensionalarray.
IntheArray,Matrix&ClusterPaletteavailablefromtheFrontPanel,wehavethebasicarrayandmatrixcontrols:
3.1 VectorsGivenavectorx
𝑥 =
𝑥$𝑥9⋮𝑥)
∈ 𝑅)
10 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
Example:Vectors
𝑥 =123
ImplementingavectorintheFrontPanel:
3.2 MatricesGivenamatrixA:
𝐴 =𝑎$$ ⋯ 𝑎$&⋮ ⋱ ⋮𝑎)$ ⋯ 𝑎)&
∈ 𝑅)-&
Example:Matrices
𝐴 = 0 1−2 −3
FrontPanel:
3.2.1 Transpose
TheTransposeofmatrixA:
𝐴3 =𝑎$$ ⋯ 𝑎)$⋮ ⋱ ⋮
𝑎$& ⋯ 𝑎)&∈ 𝑅&-)
Example:Transpose
11 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
𝐴3 = 0 1−2 −3
3= 0 −2
1 −3
FrontPanel:
BlockDiagram:
3.2.2 Diagonal
TheDiagonalelementsofmatrixAisthevector
𝑑𝑖𝑎𝑔(𝐴) =
𝑎$$𝑎99⋮𝑎::
∈ 𝑅:;<=>(-,&)
Example:Diagonal
FrontPanel:
BlockDiagram:
TheDiagonalmatrixΛisgivenby:
12 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
Λ =
𝜆$ 0 ⋯ 00 𝜆9 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 𝜆)
∈ 𝑅)-)
GiventheIdentitymatrixI:
𝐼 =
1 0 ⋯ 00 1 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 1
∈ 𝑅)-&
Example:IdentityMatrix
FrontPanel:
BlockDiagram:
3.2.3 MatrixMultiplication
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-:,then
𝐶 = 𝐴𝐵 ∈ 𝑅)-:
where
𝑐UV = 𝑎UW𝑏WV
)
W;$
Example:MatrixMultiplication
FrontPanel:
13 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
BlockDiagram:
Note!
𝐴𝐵 ≠ 𝐵𝐴
𝐴 𝐵𝐶 = 𝐴𝐵 𝐶
𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵
→ProvethisinLabVIEW
3.2.4 MatrixAddition
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅)-&,then
𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-&
Example:MatrixAddition
FrontPanel:
BlockDiagram:
14 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
Note!Thereisnospecialfunctionformatrixaddition,justusethestandardaddfunctionintheNumericpalette.
3.2.5 Determinant
Givenamatrix 𝐴 ∈ 𝑅)-),thentheDeterminantisgiven:
det 𝐴 = 𝐴
Givena2x2matrix
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Then
det 𝐴 = 𝐴 = 𝑎$$𝑎99 − 𝑎9$𝑎$9
Example:Determinant
FrontPanel:
BlockDiagram:
Noticethat
15 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
det 𝐴𝐵 = det 𝐴 det 𝐵
and
det 𝐴3 = det(𝐴)
→ProvethisinLabVIEW
3.2.6 InverseMatrices
Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅)-) isdefinedby:
𝐴I$
if
𝐴𝐴I$ = 𝐴I$𝐴 = 𝐼
Fora2x2matrixwehave:
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Theinverse 𝐴I$ isgivenby
𝐴I$ =1
det(𝐴)𝑎99 −𝑎$9−𝑎9$ 𝑎$$ ∈ 𝑅9-9
Example:Inverse
FrontPanel:
BlockDiagram:
Noticethat:
𝐴𝐴I$ = 𝐴I$𝐴 = 𝐼
16 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
→ProvethisinLabVIEW
3.3 EigenvaluesGiven 𝐴 ∈ 𝑅)-),thentheEigenvaluesisdefinedas:
det 𝜆𝐼 − 𝐴 = 0
Example:Eigenvalues
FrontPanel:
BlockDiagram:
3.4 SolvingLinearEquationsGiventhelinearequation
𝐴𝑥 = 𝑏
withthesolution:
𝑥 = 𝐴I$𝑏
(AssumingthattheinverseofAexists)
Example:SolvingLinearEquations
Theequations
𝑥$ + 2𝑥9 = 53𝑥$ + 4𝑥9 = 6
17 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
maybewritten
𝐴𝑥 = 𝑏
1 23 4
𝑥$𝑥9 = 5
6
where
𝐴 = 1 23 4
𝑥 =𝑥$𝑥9
𝑏 = 56
Thesolutionis:
FrontPanel:
BlockDiagram:
Or:
3.5 LUfactorizationLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈
where
18 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
Lisalowertriangularmatrix
Uisauppertriangularmatrix
Example:LUFactorization
FrontPanel:
BlockDiagram:
OrsometimesLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈
where
Disadiagonalmatrix
Example:LUFactorization
FrontPanel:
BlockDiagram:
19 LinearAlgebraPaletteinLabVIEW
Tutorial:LinearAlgebrainLabVIEW
3.6 TheSingularValueDecomposition(SVD)TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝑈𝑆𝑉3
where
Uisaorthogonalmatrix
Visaorthogonalmatrix
Sisadiagonalsingularmatrix
Example:SVDDecomposition
FrontPanel:
BlockDiagram:
20
4 LabVIEWMathScriptRTModule
YoucanworkwithLabVIEWMathScriptthrougheitheroftwointerfaces:the“LabVIEWMathScriptInteractiveWindow”orthe“MathScriptNode”.
YoucanworkwithLabVIEWMathScriptRTModulethroughbothinteractiveandprogrammaticinterfaces.Foraninteractiveinterfaceinwhichyoucanload,save,design,andexecuteyour.mfilescripts,youcanworkwiththe“MathScriptInteractiveWindow”.Todeployyour.mfilescriptsaspartofaLabVIEWapplicationandcombinegraphicalandtextualprogramming,youcanworkwiththe“MathScriptNode”.
TheLabVIEWMathScriptRTModulecomplementstraditionalLabVIEWgraphicalprogrammingforsuchtasksasalgorithmdevelopment,signalprocessing,andanalysis.TheLabVIEWMathScriptRTModulespeedsuptheseandothertasksbygivingusersasingleenvironmentinwhichtheycanchoosethemosteffectivesyntax,whethertextual,graphical,oracombinationofthetwo.Inaddition,youcanexploitthebestofLabVIEWandthousandsofpubliclyavailable.mfilescriptsfromtheweb,textbooks,oryourownexistingm-scriptapplications.LabVIEWMathScriptRTModuleisabletoprocessyourfilescreatedusingthecurrentMathScriptsyntaxand,forbackwardscompatibility,filescreatedusinglegacyMathScriptsyntaxes.LabVIEWMathScriptRTModulecanalsoprocesscertainofyourfilesutilizingothertext-basedsyntaxes,suchasfilesyoucreatedusingMATLABsoftware.BecausetheMathScriptRTengineisusedtoprocessscriptscontainedinaMathScriptWindowsorMathScriptNode,andbecausetheMathScriptRTenginedoesnotsupportallsyntaxes,notallexistingtext-basedscriptsaresupported.
LabVIEWMathScriptRTModulesupportsmostofthefunctionalityavailableinMATLAB,thesyntaxisalsosimilar.
Formoredetails,seehttp://zone.ni.com/devzone/cda/tut/p/id/3257
21
5 LabVIEWMathScriptRequires:MathScriptRTModule
The“LabVIEWMathScriptWindow”isaninteractiveinterfaceinwhichyoucanenter.mfilescriptcommandsandseeimmediateresults,variablesandcommandshistory.Thewindowincludesacommand-lineinterfacewhereyoucanentercommandsone-by-oneforquickcalculations,scriptdebuggingorlearning.Alternatively,youcanenterandexecutegroupsofcommandsthroughascripteditorwindow.
Asyouwork,avariabledisplayupdatestoshowthegraphical/textualresultsandahistorywindowtracksyourcommands.Thehistoryviewfacilitatesalgorithmdevelopmentbyallowingyoutousetheclipboardtoreuseyourpreviouslyexecutedcommands.
Youcanusethe“LabVIEWMathScriptWindow”toentercommandsoneattime.Youalsocanenterbatchscriptsinasimpletexteditorwindow,loadedfromatextfile,orimportedfromaseparatetexteditor.The“LabVIEWMathScriptWindow”providesimmediatefeedbackinavarietyofforms,suchasgraphsandtext.
Example:
22 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
5.1 HelpYoumayalsotypehelpinyourcommandwindow
>>help
Ormorespecific,e.g.,
>>help plot
5.2 ExamplesIadviseyoutotestalltheexamplesinthistextinLabVIEWMathScriptinordertogetfamiliarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelikethis:
>> …
23 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
ThisiscommandsyoushouldwriteintheCommandWindow.
YoutypeallyourcommandsintheCommandWindow.Iwillusethesymbol“>>”toillustratethatthecommandsshouldbewrittenintheCommandWindow.
Example:Matrices
Definingthefollowingmatrix
𝐴 = 1 20 3
Thesyntaxisasfollows:
>> A = [1 2;0 3]
Or
>> A = [1,2;0,3]
Ifyou,foranexample,wanttofindtheanswerto
𝑎 + 𝑏,𝑤ℎ𝑒𝑟𝑒𝑎 = 4, 𝑏 = 3
>>a=4 >>b=3 >>a+b
MathScriptthenresponds:
ans = 7
MathScriptprovidesasimplewaytodefinesimplearraysusingthesyntax:“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 =
24 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
1 2 3 4 5
assignstothevariablenamedarianarraywiththevalues1,2,3,4,and5,sincethedefaultvalueof1isusedastheincrementer.
Notethattheindexingisone-based,whichistheusualconventionformatricesinmathematics.Thisisatypicalforprogramminglanguages,whosearraysmoreoftenstartwithzero.
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
25 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
1 1 1
5.3 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
5.4 FlowControlThischapterexplainsthebasicconceptsofflowcontrolinMathScript.
Thetopicsareasfollows:
• If-elsestatement• Switchandcasestatement• Forloop• Whileloop
5.4.1 If-elseStatement
Theifstatementevaluatesalogicalexpressionandexecutesagroupofstatementswhentheexpressionistrue.Theoptionalelseifandelsekeywordsprovidefortheexecutionofalternategroupsofstatements.Anendkeyword,whichmatchestheif,terminatesthelastgroupofstatements.Thegroupsofstatementsaredelineatedbythefourkeywords—nobracesorbracketsareinvolved.
Example:If-ElseStatement
Testthefollowingcode:
26 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end
5.4.2 SwitchandCaseStatement
Theswitchstatementexecutesgroupsofstatementsbasedonthevalueofavariableorexpression.Thekeywordscaseandotherwisedelineatethegroups.Onlythefirstmatchingcaseisexecuted.Theremustalwaysbeanendtomatchtheswitch.
Example:SwitchandCaseStatement
Testthefollowingcode:
n=2 switch(n) case 1 M = eye(n) case 2 M = zeros(n) case 3 M = ones(n) end
5.4.3 Forloop
Theforlooprepeatsagroupofstatementsafixed,predeterminednumberoftimes.Amatchingenddelineatesthestatements.
Example:ForLoop
Testthefollowingcode:
m=5 for n = 1:m r(n) = rank(magic(n)); end r
5.4.4 Whileloop
Thewhilelooprepeatsagroupofstatementsanindefinitenumberoftimesundercontrolofalogicalcondition.Amatchingenddelineatesthestatements.
27 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
Example:WhileLoop
Testthefollowingcode:
m=5; while m > 1 m = m - 1; zeros(m) end
28 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
5.5 PlottingThischapterexplainsthebasicconceptsofcreatingplotsinMathScript.
Topics:
• BasicPlotcommands
Example:Plotting
Functionplotcanbeusedtoproduceagraphfromtwovectorsxandy.Thecode:
x = 0:pi/100:2*pi; y = sin(x); plot(x,y)
producesthefollowingfigureofthesinefunction:
Example:Plotting
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})')
29 LabVIEWMathScript
Tutorial:LinearAlgebrainLabVIEW
hidden off
Thiscodeproducesthefollowing3Dplot:
30 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
6 LinearAlgebraExamplesusingMathScript
Requires:MathScriptRTModule
Linearalgebraisabranchofmathematicsconcernedwiththestudyofmatrices,vectors,vectorspaces(alsocalledlinearspaces),linearmaps(alsocalledlineartransformations),andsystemsoflinearequations.
MathScriptarewellsuitedforLinearAlgebra.
6.1 VectorsGivenavectorx
𝑥 =
𝑥$𝑥9⋮𝑥)
∈ 𝑅)
Example:Vectors
Giventhefollowingvector
𝑥 =123
>> x=[1; 2; 3] x = 1 2 3
TheTransposeofvectorx:
𝑥3 = 𝑥$ 𝑥9 ⋯ 𝑥) ∈ 𝑅$-)
>> x' ans = 1 2 3
TheLengthofvectorx:
31 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
𝑥 = 𝑥3𝑥 = 𝑥$9 + 𝑥99 + ⋯+ 𝑥)9
Orthogonality:
𝑥3𝑦 = 0
6.2 MatricesGivenamatrixA:
𝐴 =𝑎$$ ⋯ 𝑎$&⋮ ⋱ ⋮𝑎)$ ⋯ 𝑎)&
∈ 𝑅)-&
Example:Matrices
Giventhefollowingmatrix:
𝐴 = 0 1−2 −3
>> A=[0 1;-2 -3] A = 0 1 -2 -3
6.2.1 Transpose
TheTransposeofmatrixA:
𝐴3 =𝑎$$ ⋯ 𝑎)$⋮ ⋱ ⋮
𝑎$& ⋯ 𝑎)&∈ 𝑅&-)
Example:Transpose
Giventhematrix:
𝐴3 = 0 1−2 −3
3= 0 −2
1 −3
>> A' ans = 0 -2 1 -3
32 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
6.2.2 Diagonal
TheDiagonalelementsofmatrixAisthevector
𝑑𝑖𝑎𝑔(𝐴) =
𝑎$$𝑎99⋮𝑎::
∈ 𝑅:;<=>(-,&)
Example:Diagonal
FindthediagonalelementsofmatrixA:
>> diag(A) ans = 0 -3
TheDiagonalmatrixΛisgivenby:
Λ =
𝜆$ 0 ⋯ 00 𝜆9 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 𝜆)
∈ 𝑅)-)
GiventheIdentitymatrixI:
𝐼 =
1 0 ⋯ 00 1 ⋯ 0⋮ ⋮ ⋱ ⋮0 0 ⋯ 1
∈ 𝑅)-&
Example:IdentityMatrix
Getthe3x3Identitymatrix:
>> eye(3) ans = 1 0 0 0 1 0 0 0 1
6.2.3 Triangular
LowerTriangularmatrixL:
𝐿 =. 0 0⋮ ⋱ 0. ⋯ .
33 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
UpperTriangularmatrixU:
𝑈 =. ⋯ .0 ⋱ ⋮0 0 .
6.2.4 MatrixMultiplication
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-:,then
𝐶 = 𝐴𝐵 ∈ 𝑅)-:
where
𝑐UV = 𝑎UW𝑏WV
)
W;$
Example:MatrixMultiplication
Matrixmultiplication:
>> 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!
𝐴𝐵 ≠ 𝐵𝐴
𝐴 𝐵𝐶 = 𝐴𝐵 𝐶
𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵
6.2.5 MatrixAddition
Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅)-&,then
𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-&
34 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
Example:MatrixAddition
Matrixaddition:
>> A=[0 1;-2 -3] >> B=[1 0;3 -2] >> A+B ans = 1 1 1 -5
6.2.6 Determinant
Givenamatrix 𝐴 ∈ 𝑅)-),thentheDeterminantisgiven:
det 𝐴 = 𝐴
Givena2x2matrix
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Then
det 𝐴 = 𝐴 = 𝑎$$𝑎99 − 𝑎9$𝑎$9
Example:Determinant
Findthedeterminant:
A = 0 1 -2 -3 >> det(A) ans = 2
Noticethat
det 𝐴𝐵 = det 𝐴 det 𝐵
and
det 𝐴3 = det(𝐴)
35 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
Example:Determinant
Determinants:
>> det(A*B) ans = -4 >> det(A)*det(B) ans = -4 >> det(A') ans = 2 >> det(A) ans = 2
6.2.7 InverseMatrices
Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅)-) isdefinedby:
𝐴I$
if
𝐴𝐴I$ = 𝐴I$𝐴 = 𝐼
Fora2x2matrixwehave:
𝐴 =𝑎$$ 𝑎$9𝑎9$ 𝑎99 ∈ 𝑅9-9
Theinverse 𝐴I$ isgivenby
𝐴I$ =1
det(𝐴)𝑎99 −𝑎$9−𝑎9$ 𝑎$$ ∈ 𝑅9-9
Example:InverseMatrices
Inversematrix:
A = 0 1 -2 -3 >> inv(A) ans = -1.5000 -0.5000 1.0000 0
Noticethat:
36 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
𝐴𝐴I$ = 𝐴I$𝐴 = 𝐼
→ProvethisinMathScript
6.3 EigenvaluesGiven 𝐴 ∈ 𝑅)-),thentheEigenvaluesisdefinedas:
det 𝜆𝐼 − 𝐴 = 0
Example:Eigenvalues
FindtheEigenvalues:
A = 0 1 -2 -3 >> eig(A) ans = -1 -2
6.4 SolvingLinearEquationsGiventhelinearequation
𝐴𝑥 = 𝑏
withthesolution:
𝑥 = 𝐴I$𝑏
(AssumingthattheinverseofAexists)
Example:SolvingLinearEquations
Solvingthefollowingequation:
Theequations
𝑥$ + 2𝑥9 = 53𝑥$ + 4𝑥9 = 6
maybewritten
𝐴𝑥 = 𝑏
37 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
1 23 4
𝑥$𝑥9 = 5
6
where
𝐴 = 1 23 4
𝑥 =𝑥$𝑥9
𝑏 = 56
Thesolutionis:
A = 1 2 3 4 >> b=[5;6] b = 5 6 >> x=inv(A)*b x = -4.0000 4.5000
InMathScriptyoucouldalsowrite“x=A\b”,whichshouldgivethesameanswer.ThissyntaxcanalsobeusedwhentheinverseofAdon’texists.
Example:SolvingLinearEquations
Illegaloperation:
>> 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
6.5 LUfactorizationLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈
where
38 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
Lisalowertriangularmatrix
Uisauppertriangularmatrix
TheMathScriptsyntaxis[L,U]=lu(A)
Example:LUFactorization
FindLandU:
>> 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 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈
where
Disadiagonalmatrix
TheMathScriptsyntaxis[L,U,P]=lu(A)
Example:LUFactorization
FindL,UandP:
>> A=[1 2;3 4] A = 1 2 3 4 >> [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
6.6 TheSingularValueDecomposition(SVD)
39 LinearAlgebraExamplesusingMathScript
Tutorial:LinearAlgebrainLabVIEW
TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅)-& isgivenby
𝐴 = 𝑈𝑆𝑉3
where
Uisaorthogonalmatrix
Visaorthogonalmatrix
Sisadiagonalsingularmatrix
Example:SVDDecomposition
FindS,VandD:
>> 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
6.7 Commands
Command Description
[L,U]=lu(A)
[L,U,P]=lu(A)LUFactorization
[U,S,V] = svd(A) SingularValueDecomposition(SVD)
40
7 MathScriptNodeThe“MathScriptNode”offersanintuitivemeansofcombininggraphicalandtextualcodewithinLabVIEW.Thefigurebelowshowsthe“MathScriptNode”ontheblockdiagram,representedbythebluerectangle.Using“MathScriptNodes”,youcanenter.mfilescripttextdirectlyorimportitfromatextfile.
YoucandefinenamedinputsandoutputsontheMathScriptNodebordertospecifythedatatotransferbetweenthegraphicalLabVIEWenvironmentandthetextualMathScriptcode.
Youcanassociate.mfilescriptvariableswithLabVIEWgraphicalprogramming,bywiringNodeinputsandoutputs.Thenyoucantransferdatabetween.mfilescriptswithyourgraphicalLabVIEWprogramming.Thetextual.mfilescriptscannowaccessfeaturesfromtraditionalLabVIEWgraphicalprogramming.
TheMathScriptNodeisavailablefromLabVIEWfromtheFunctionsPalette:Mathematics→Scripts&Formulas
41 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
IfyouclickCtrl+HyougethelpabouttheMathScriptNode:
Click“Detailedhelp”inordertogetmoreinformationabouttheMathScriptNode.
UsetheNIExampleFinderinordertofindexamples:
42 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
7.1 TransferringMathScriptNodesbetweenComputers
IfascriptinaMathScriptNodecallsauser-definedfunction,LabVIEWusesthedefaultsearchpathlisttolinkthefunctioncalltothespecified.mfile.AfteryouconfigurethedefaultsearchpathlistandsavetheVIthatcontainstheMathScriptNode,youdonotneedtoreconfiguretheMathScriptsearchpathlistwhenyouopentheVIonadifferentcomputerbecauseLabVIEWlooksforthe.mfileinthedirectorywherethe.mfilewaslocatedwhenyoulastsavedtheVI.However,youmustmaintainthesamerelativepathbetweentheVIandthe.mfile.
7.2 ExamplesExample:UsingtheMathScriptNode
HereisanexampleofhowyouusetheMathScriptNode.Ontheleftborderyouconnectinputvariablestothescript,ontherightborderyouhaveoutputvariables.Right-clickontheborderandselect“AddInput”or“AddOutput”.
43 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
Example:CallingaWindowsDLL:
Example:Usingm-filesintheMathScriptNode:
UsetheLabVIEWMathScripttocreateam-filescript(oryoumayuseMATLABtocreatethesamescript):
44 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
Right-clickontheborderoftheMathScriptNodeandselect“Import”,andthenselectthem-fileyouwanttoimportintotheNode.
45 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
Right-clickontherightborderandselect“AddOutput”.Thenright-clickontheoutputvariableandselect“CreateIndicator”.
BlockDiagram:
Theresultisasfollows(clicktheRunbutton):
Ifyou,e.g.,addthefollowingcommandintheMathScriptNode:plot(x),thefollowingwindowappears:
46 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
7.3 ExercisesUsetheMathScriptNodeandtestthesameexamplesyoudidinthepreviouschapter(Chapter6-“LinearAlgebraExamplesusingMathScript”)
47
8 WhatsNext?
8.1 MyBlogFormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
8.2 TrainingThisTrainingisapartofaserieswithotherTrainingKitsIhavemade,suchas:
• IntroductiontoLabVIEW• DataAcquisitioninLabVIEW• ControlandSimulationinLabVIEW• LabVIEWMathScript• LinearAlgebrainLabVIEW• DataloggingandSupervisoryControlinLabVIEW• WirelessDataAcquisitioninLabVIEW• IntermediateTopicsinLabVIEW• AdvancedTopicsinLabVIEW
TheseTrainingKitsareavailablefordownloadfrommyblog:http://home.hit.no/~hansha
8.3 MathScriptFunctionsIntheHelpsystemthereisdetailedinformationaboutalltheMathScriptfunctionsavailable.InadditiontotheMathScriptRTModulefunctions,differentadd-onmodulesandtoolkitsinstallsadditionalfunctions.TheLabVIEWControlDesignandSimulationModuleandLabVIEWDigitalFilterDesignToolkitinstallsalotsofadditionalfunctions.
48 MathScriptNode
Tutorial:LinearAlgebrainLabVIEW
49
QuickReference
50 QuickReference
Tutorial:LinearAlgebrainLabVIEW
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no