* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Tutorial: Linear Algebra In LabVIEW
Rotation matrix wikipedia , lookup
Linear least squares (mathematics) wikipedia , lookup
Jordan normal form wikipedia , lookup
Symmetric cone wikipedia , lookup
Exterior algebra wikipedia , lookup
Four-vector wikipedia , lookup
Eigenvalues and eigenvectors wikipedia , lookup
Matrix (mathematics) wikipedia , lookup
Determinant wikipedia , lookup
Perron–Frobenius theorem wikipedia , lookup
Non-negative matrix factorization wikipedia , lookup
Matrix calculus wikipedia , lookup
Orthogonal matrix wikipedia , lookup
Singular-value decomposition wikipedia , lookup
Gaussian elimination wikipedia , lookup
System of linear equations wikipedia , lookup
Cayley–Hamilton theorem wikipedia , lookup
UniversityCollegeofSoutheastNorway LinearAlgebrainLabVIEW Hans-PetterHalvorsen,2016-10-31 http://home.hit.no/~hansha Preface ThisdocumentexplainsthebasicconceptsofLinearAlgebraandhowyoumayuseLabVIEW forcalculationoftheseproblems. YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“AnIntroductionto LabVIEW”training.Thisdocumentisavailablefordownloadathttp://home.hit.no/~hansha/. FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/ TableofContents Preface......................................................................................................................................2 TableofContents.....................................................................................................................iii 1 2 3 IntroductiontoLabVIEW...................................................................................................1 1.1 Dataflowprogramming...............................................................................................1 1.2 Graphicalprogramming..............................................................................................2 1.3 Benefits.......................................................................................................................2 1.4 LabVIEWMathScriptRTModule................................................................................3 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 LinearAlgebraPaletteinLabVIEW....................................................................................8 3.1 Vectors........................................................................................................................9 3.2 Matrices....................................................................................................................10 3.2.1 Transpose..........................................................................................................10 iii iv TableofContents 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 6 Plotting.....................................................................................................................28 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 Tutorial:LinearAlgebrainLabVIEW v 7 8 TableofContents 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 MathScriptNode.............................................................................................................40 7.1 TransferringMathScriptNodesbetweenComputers...............................................42 7.2 Examples...................................................................................................................42 7.3 Exercises...................................................................................................................46 WhatsNext?....................................................................................................................47 8.1 MyBlog.....................................................................................................................47 8.2 Training.....................................................................................................................47 8.3 MathScriptFunctions................................................................................................47 QuickReference......................................................................................................................49 Tutorial:LinearAlgebrainLabVIEW 1 IntroductiontoLabVIEW LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational Instruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheApple Macintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,and industrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavors ofUNIX,Linux,andMacOSX.VisitNationalInstrumentsatwww.ni.com. Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”. LabVIEWofferslotsofadditionalAdd-OnsandToolkits. ThispaperispartofaserieswithLabVIEWpapers: • • • • • • • • • IntroductiontoLabVIEW LinearAlgebrainLabVIEW DataAcquisitionandInstrumentControlinLabVIEW ControlDesignandSimulationinLabVIEW SignalProcessinginLabVIEW DataloggingandSupervisoryControlinLabVIEW SystemidentificationinLabVIEW ModelbasedControlinLabVIEW AdvancedTopicsinLabVIEW Eachpapermaybeusedindependentlyofeachother. 1.1 Dataflowprogramming TheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflow programminglanguage.Executionisdeterminedbythestructureofagraphicalblock diagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodes bydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasall itsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodes simultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmultithreadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexes multipleOSthreadsoverthenodesreadyforexecution. 1 2 IntroductiontoLabVIEW 1.2 Graphicalprogramming LabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle. LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthree components:ablockdiagram,afrontpanel,andaconnectorpanel.Thelastisusedto representtheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthe frontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtual instrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusa virtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauser interface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinesthe inputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcan beeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram. Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragging anddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar. TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthe documentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside, butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality "G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthatthe programmerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthe topologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystems offerthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreate distributedapplications,whichcommunicatebyaclient/serverscheme,andaretherefore easiertoimplementduetotheinherentlyparallelnatureofG-code. 1.3 Benefits OnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportfor accessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypes ofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresent themselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacesto communicatewithhardwaredevices.Theprovideddriverinterfacessaveprogram developmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeople withlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareduced timeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardware drivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlya fewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit) functions,providesplatformindependenthardwareaccesstonumerousdataacquisition Tutorial:LinearAlgebrainLabVIEW 3 IntroductiontoLabVIEW andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows, MacOSXandLinuxplatforms. FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/ 1.4 LabVIEWMathScriptRTModule TheLabVIEWMathScriptRTModuleisanadd-onmoduletoLabVIEW.WithLabVIEW MathScriptRTModuleyoucan: • • • • Deployyourcustom.mfilestoNIreal-timehardware ReusemanyofyourscriptscreatedwithTheMathWorks,Inc.MATLAB®softwareand others Developyour.mfileswithaninteractivecommand-lineinterface EmbedyourscriptsintoyourLabVIEWapplicationsusingtheMathScriptNode Tutorial:LinearAlgebrainLabVIEW 2 IntroductiontoLinear Algebra GivenamatrixA: 𝑎$$ 𝐴= ⋮ 𝑎)$ ⋯ ⋱ ⋯ 𝑎$& ⋮ ∈ 𝑅)-& 𝑎)& Example: 𝐴= 2.1.1 0 1 −2 −3 Transpose TheTransposeofmatrixA: 𝐴3 = 2.1.2 0 −2 1 −3 Diagonal TheDiagonalelementsofmatrixAisthevector 𝑎$$ 𝑎99 𝑑𝑖𝑎𝑔(𝐴) = ⋮ ∈ 𝑅:;<=>(-,&) 𝑎:: TheDiagonalmatrixΛisgivenby: 𝜆$ 0 Λ= ⋮ 0 0 𝜆9 ⋮ 0 ⋯ ⋯ ⋱ ⋯ GiventheIdentitymatrixI: 4 0 0 ∈ 𝑅)-) ⋮ 𝜆) 5 1 0 ⋯ 0 1 ⋯ 𝐼= ⋮ ⋮ ⋱ 0 0 ⋯ 2.1.3 IntroductiontoLinearAlgebra 0 0 ∈ 𝑅)-& ⋮ 1 MatrixMultiplication Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-: ,then 𝐶 = 𝐴𝐵 ∈ 𝑅)-: 2.1.4 MatrixAddition Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅)-& ,then 𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-& 2.1.5 Determinant Givenamatrix 𝐴 ∈ 𝑅)-) ,thentheDeterminantisgiven: det 𝐴 = 𝐴 Givena2x2matrix 𝑎$$ 𝐴= 𝑎 9$ 𝑎$9 9-9 𝑎99 ∈ 𝑅 Then det 𝐴 = 𝐴 = 𝑎$$ 𝑎99 − 𝑎9$ 𝑎$9 Noticethat det 𝐴𝐵 = det 𝐴 det 𝐵 and det 𝐴3 = det(𝐴) 2.1.6 InverseMatrices Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅)-) isdefinedby: 𝐴I$ Tutorial:LinearAlgebrainLabVIEW 6 IntroductiontoLinearAlgebra if 𝐴𝐴I$ = 𝐴I$ 𝐴 = 𝐼 Fora2x2matrixwehave: 𝑎$$ 𝐴= 𝑎 9$ 𝑎$9 9-9 𝑎99 ∈ 𝑅 Theinverse 𝐴I$ isgivenby 𝐴I$ = 1 𝑎99 det(𝐴) −𝑎9$ −𝑎$9 9-9 𝑎$$ ∈ 𝑅 2.2 Eigenvalues Given 𝐴 ∈ 𝑅)-) ,thentheEigenvaluesisdefinedas: det 𝜆𝐼 − 𝐴 = 0 2.3 SolvingLinearEquations Giventhelinearequation 𝐴𝑥 = 𝑏 withthesolution: 𝑥 = 𝐴I$ 𝑏 (AssumingthattheinverseofAexists) Example: Theequations 𝑥$ + 2𝑥9 = 5 3𝑥$ + 4𝑥9 = 6 maybewritten 𝐴𝑥 = 𝑏 1 2 𝑥$ 5 = 3 4 𝑥9 6 where Tutorial:LinearAlgebrainLabVIEW 7 𝐴= IntroductiontoLinearAlgebra 1 2 3 4 𝑥$ 𝑥= 𝑥 9 𝑏= 5 6 2.4 LUfactorization LUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝐿𝑈 where Lisalowertriangularmatrix Uisauppertriangularmatrix OrsometimesLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈 where Disadiagonalmatrix 2.5 TheSingularValueDecomposition(SVD) TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝑈𝑆𝑉 3 where Uisaorthogonalmatrix Visaorthogonalmatrix Sisadiagonalsingularmatrix Tutorial:LinearAlgebrainLabVIEW 3 LinearAlgebraPalettein LabVIEW ForanIntroductiontoLabVIEW,seethetraining:“AnIntroductiontoLabVIEW”.Youmay downloaditfrommyBlog:http://home.hit.no/~hansha/ UsetheLinearAlgebraPaletteinordertosolveLinearAlgebraproblemswiththeuseof Graphicalprogramming. IntheMatrixSubPalettewehavethefollowingfunctions: 8 9 LinearAlgebraPaletteinLabVIEW LabVIEWusesarraystorepresentsvectorsandmatrices.Avectorisrepresentedasaone dimensionalarray,whileamatrixisrepresentedasatwodimensionalarray. IntheArray,Matrix&ClusterPaletteavailablefromtheFrontPanel,wehavethebasicarray andmatrixcontrols: 3.1 Vectors Givenavectorx 𝑥$ 𝑥9 𝑥 = ⋮ ∈ 𝑅) 𝑥) Tutorial:LinearAlgebrainLabVIEW 10 LinearAlgebraPaletteinLabVIEW Example:Vectors 1 𝑥= 2 3 ImplementingavectorintheFrontPanel: 3.2 Matrices GivenamatrixA: 𝑎$$ 𝐴= ⋮ 𝑎)$ ⋯ ⋱ ⋯ 𝑎$& ⋮ ∈ 𝑅)-& 𝑎)& Example:Matrices 𝐴= 0 1 −2 −3 FrontPanel: 3.2.1 Transpose TheTransposeofmatrixA: 𝑎$$ 𝐴 = ⋮ 𝑎$& 3 ⋯ ⋱ ⋯ 𝑎)$ ⋮ ∈ 𝑅&-) 𝑎)& Example:Transpose Tutorial:LinearAlgebrainLabVIEW 11 𝐴3 = 0 1 −2 −3 LinearAlgebraPaletteinLabVIEW 3 = 0 −2 1 −3 FrontPanel: BlockDiagram: 3.2.2 Diagonal TheDiagonalelementsofmatrixAisthevector 𝑎$$ 𝑎99 𝑑𝑖𝑎𝑔(𝐴) = ⋮ ∈ 𝑅:;<=>(-,&) 𝑎:: Example:Diagonal FrontPanel: BlockDiagram: TheDiagonalmatrixΛisgivenby: Tutorial:LinearAlgebrainLabVIEW 12 𝜆$ 0 Λ= ⋮ 0 0 𝜆9 ⋮ 0 ⋯ ⋯ ⋱ ⋯ LinearAlgebraPaletteinLabVIEW 0 0 ∈ 𝑅)-) ⋮ 𝜆) GiventheIdentitymatrixI: 1 0 ⋯ 0 1 ⋯ 𝐼= ⋮ ⋮ ⋱ 0 0 ⋯ 0 0 ∈ 𝑅)-& ⋮ 1 Example:IdentityMatrix FrontPanel: BlockDiagram: 3.2.3 MatrixMultiplication Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-: ,then 𝐶 = 𝐴𝐵 ∈ 𝑅)-: where ) 𝑎UW 𝑏WV 𝑐UV = W;$ Example:MatrixMultiplication FrontPanel: Tutorial:LinearAlgebrainLabVIEW 13 LinearAlgebraPaletteinLabVIEW BlockDiagram: Note! 𝐴𝐵 ≠ 𝐵𝐴 𝐴 𝐵𝐶 = 𝐴𝐵 𝐶 𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶 𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵 →ProvethisinLabVIEW 3.2.4 MatrixAddition Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅)-& ,then 𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-& Example:MatrixAddition FrontPanel: BlockDiagram: Tutorial:LinearAlgebrainLabVIEW 14 LinearAlgebraPaletteinLabVIEW Note!Thereisnospecialfunctionformatrixaddition,justusethestandardaddfunctionin theNumericpalette. 3.2.5 Determinant Givenamatrix 𝐴 ∈ 𝑅)-) ,thentheDeterminantisgiven: det 𝐴 = 𝐴 Givena2x2matrix 𝑎$$ 𝐴= 𝑎 9$ 𝑎$9 9-9 𝑎99 ∈ 𝑅 Then det 𝐴 = 𝐴 = 𝑎$$ 𝑎99 − 𝑎9$ 𝑎$9 Example:Determinant FrontPanel: BlockDiagram: Noticethat Tutorial:LinearAlgebrainLabVIEW 15 LinearAlgebraPaletteinLabVIEW det 𝐴𝐵 = det 𝐴 det 𝐵 and det 𝐴3 = det(𝐴) →ProvethisinLabVIEW 3.2.6 InverseMatrices Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅)-) isdefinedby: 𝐴I$ if 𝐴𝐴I$ = 𝐴I$ 𝐴 = 𝐼 Fora2x2matrixwehave: 𝑎$$ 𝐴= 𝑎 9$ 𝑎$9 9-9 𝑎99 ∈ 𝑅 Theinverse 𝐴I$ isgivenby 𝐴I$ = 1 𝑎99 det(𝐴) −𝑎9$ −𝑎$9 9-9 𝑎$$ ∈ 𝑅 Example:Inverse FrontPanel: BlockDiagram: Noticethat: 𝐴𝐴I$ = 𝐴I$ 𝐴 = 𝐼 Tutorial:LinearAlgebrainLabVIEW 16 LinearAlgebraPaletteinLabVIEW →ProvethisinLabVIEW 3.3 Eigenvalues Given 𝐴 ∈ 𝑅)-) ,thentheEigenvaluesisdefinedas: det 𝜆𝐼 − 𝐴 = 0 Example:Eigenvalues FrontPanel: BlockDiagram: 3.4 SolvingLinearEquations Giventhelinearequation 𝐴𝑥 = 𝑏 withthesolution: 𝑥 = 𝐴I$ 𝑏 (AssumingthattheinverseofAexists) Example:SolvingLinearEquations Theequations 𝑥$ + 2𝑥9 = 5 3𝑥$ + 4𝑥9 = 6 Tutorial:LinearAlgebrainLabVIEW 17 LinearAlgebraPaletteinLabVIEW maybewritten 𝐴𝑥 = 𝑏 1 2 𝑥$ 5 = 3 4 𝑥9 6 where 𝐴= 1 2 3 4 𝑥$ 𝑥= 𝑥 9 𝑏= 5 6 Thesolutionis: FrontPanel: BlockDiagram: Or: 3.5 LUfactorization LUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝐿𝑈 where Tutorial:LinearAlgebrainLabVIEW 18 LinearAlgebraPaletteinLabVIEW Lisalowertriangularmatrix Uisauppertriangularmatrix Example:LUFactorization FrontPanel: BlockDiagram: OrsometimesLUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝐿𝑈 = 𝐿𝐷𝑈 where Disadiagonalmatrix Example:LUFactorization FrontPanel: BlockDiagram: Tutorial:LinearAlgebrainLabVIEW 19 LinearAlgebraPaletteinLabVIEW 3.6 TheSingularValueDecomposition(SVD) TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝑈𝑆𝑉 3 where Uisaorthogonalmatrix Visaorthogonalmatrix Sisadiagonalsingularmatrix Example:SVDDecomposition FrontPanel: BlockDiagram: Tutorial:LinearAlgebrainLabVIEW 4 LabVIEWMathScriptRT Module YoucanworkwithLabVIEWMathScriptthrougheitheroftwointerfaces:the“LabVIEW MathScriptInteractiveWindow”orthe“MathScriptNode”. YoucanworkwithLabVIEWMathScriptRTModulethroughbothinteractiveand programmaticinterfaces.Foraninteractiveinterfaceinwhichyoucanload,save,design, andexecuteyour.mfilescripts,youcanworkwiththe“MathScriptInteractiveWindow”.To deployyour.mfilescriptsaspartofaLabVIEWapplicationandcombinegraphicaland textualprogramming,youcanworkwiththe“MathScriptNode”. TheLabVIEWMathScriptRTModulecomplementstraditionalLabVIEWgraphical programmingforsuchtasksasalgorithmdevelopment,signalprocessing,andanalysis.The LabVIEWMathScriptRTModulespeedsuptheseandothertasksbygivingusersasingle environmentinwhichtheycanchoosethemosteffectivesyntax,whethertextual,graphical, oracombinationofthetwo.Inaddition,youcanexploitthebestofLabVIEWandthousands ofpubliclyavailable.mfilescriptsfromtheweb,textbooks,oryourownexistingm-script applications.LabVIEWMathScriptRTModuleisabletoprocessyourfilescreatedusingthe currentMathScriptsyntaxand,forbackwardscompatibility,filescreatedusinglegacy MathScriptsyntaxes.LabVIEWMathScriptRTModulecanalsoprocesscertainofyourfiles utilizingothertext-basedsyntaxes,suchasfilesyoucreatedusingMATLABsoftware. BecausetheMathScriptRTengineisusedtoprocessscriptscontainedinaMathScript WindowsorMathScriptNode,andbecausetheMathScriptRTenginedoesnotsupportall syntaxes,notallexistingtext-basedscriptsaresupported. LabVIEWMathScriptRTModulesupportsmostofthefunctionalityavailableinMATLAB,the syntaxisalsosimilar. Formoredetails,seehttp://zone.ni.com/devzone/cda/tut/p/id/3257 20 5 LabVIEWMathScript Requires:MathScriptRTModule The“LabVIEWMathScriptWindow”isaninteractiveinterfaceinwhichyoucanenter.mfile scriptcommandsandseeimmediateresults,variablesandcommandshistory.Thewindow includesacommand-lineinterfacewhereyoucanentercommandsone-by-oneforquick calculations,scriptdebuggingorlearning.Alternatively,youcanenterandexecutegroupsof commandsthroughascripteditorwindow. Asyouwork,avariabledisplayupdatestoshowthegraphical/textualresultsandahistory windowtracksyourcommands.Thehistoryviewfacilitatesalgorithmdevelopmentby allowingyoutousetheclipboardtoreuseyourpreviouslyexecutedcommands. Youcanusethe“LabVIEWMathScriptWindow”toentercommandsoneattime.Youalso canenterbatchscriptsinasimpletexteditorwindow,loadedfromatextfile,orimported fromaseparatetexteditor.The“LabVIEWMathScriptWindow”providesimmediate feedbackinavarietyofforms,suchasgraphsandtext. Example: 21 22 LabVIEWMathScript 5.1 Help Youmayalsotypehelpinyourcommandwindow >>help Ormorespecific,e.g., >>help plot 5.2 Examples IadviseyoutotestalltheexamplesinthistextinLabVIEWMathScriptinordertoget familiarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelike this: >> … Tutorial:LinearAlgebrainLabVIEW 23 LabVIEWMathScript ThisiscommandsyoushouldwriteintheCommandWindow. YoutypeallyourcommandsintheCommandWindow.Iwillusethesymbol“>>”to illustratethatthecommandsshouldbewrittenintheCommandWindow. Example:Matrices Definingthefollowingmatrix 𝐴= 1 2 0 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(orassignsanewvaluetoanexistingvariablewiththename array)whichisanarrayconsistingofthevalues1,3,5,7,and9.Thatis,thearraystartsat1 (theinitvalue),incrementswitheachstepfromthepreviousvalueby2(theincrement value),andstopsonceitreaches(ortoavoidexceeding)9(theterminatorvalue). Theincrementvaluecanactuallybeleftoutofthissyntax(alongwithoneofthecolons),to useadefaultvalueof1. >> ari = 1:5 ari = Tutorial:LinearAlgebrainLabVIEW 24 LabVIEWMathScript 1 2 3 4 5 assignstothevariablenamedarianarraywiththevalues1,2,3,4,and5,sincethedefault valueof1isusedastheincrementer. Notethattheindexingisone-based,whichistheusualconventionformatricesin mathematics.Thisisatypicalforprogramminglanguages,whosearraysmoreoftenstart withzero. Matricescanbedefinedbyseparatingtheelementsofarowwithblankspaceorcommaand usingasemicolontoterminateeachrow.Thelistofelementsshouldbesurroundedby squarebrackets:[].Parentheses:()areusedtoaccesselementsandsubarrays(theyarealso usedtodenoteafunctionargumentlist). >> 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].For example,asubmatrixtakenfromrows2through4andcolumns3through4canbewritten as: >> A(2:4,3:4) ans = 11 8 7 12 14 1 Asquareidentitymatrixofsizencanbegeneratedusingthefunctioneye,andmatricesof anysizewithzerosoronescanbegeneratedwiththefunctionszerosandones,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 Tutorial:LinearAlgebrainLabVIEW 25 LabVIEWMathScript 1 1 1 5.3 Usefulcommands Herearesomeusefulcommands: 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 FlowControl ThischapterexplainsthebasicconceptsofflowcontrolinMathScript. Thetopicsareasfollows: • • • • If-elsestatement Switchandcasestatement Forloop Whileloop 5.4.1 If-elseStatement Theifstatementevaluatesalogicalexpressionandexecutesagroupofstatementswhenthe expressionistrue.Theoptionalelseifandelsekeywordsprovidefortheexecutionof alternategroupsofstatements.Anendkeyword,whichmatchestheif,terminatesthelast groupofstatements.Thegroupsofstatementsaredelineatedbythefourkeywords—no bracesorbracketsareinvolved. Example:If-ElseStatement Testthefollowingcode: Tutorial:LinearAlgebrainLabVIEW 26 LabVIEWMathScript n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end 5.4.2 SwitchandCaseStatement Theswitchstatementexecutesgroupsofstatementsbasedonthevalueofavariableor expression.Thekeywordscaseandotherwisedelineatethegroups.Onlythefirstmatching caseisexecuted.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.A matchingenddelineatesthestatements. Example:ForLoop Testthefollowingcode: m=5 for n = 1:m r(n) = rank(magic(n)); end r 5.4.4 Whileloop Thewhilelooprepeatsagroupofstatementsanindefinitenumberoftimesundercontrolof alogicalcondition.Amatchingenddelineatesthestatements. Tutorial:LinearAlgebrainLabVIEW 27 Example:WhileLoop Testthefollowingcode: m=5; while m > 1 m = m - 1; zeros(m) end Tutorial:LinearAlgebrainLabVIEW LabVIEWMathScript 28 LabVIEWMathScript 5.5 Plotting ThischapterexplainsthebasicconceptsofcreatingplotsinMathScript. 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})') Tutorial:LinearAlgebrainLabVIEW 29 LabVIEWMathScript hidden off Thiscodeproducesthefollowing3Dplot: Tutorial:LinearAlgebrainLabVIEW 30 LinearAlgebraExamplesusingMathScript 6 LinearAlgebraExamples usingMathScript Requires:MathScriptRTModule Linearalgebraisabranchofmathematicsconcernedwiththestudyofmatrices,vectors, vectorspaces(alsocalledlinearspaces),linearmaps(alsocalledlineartransformations),and systemsoflinearequations. MathScriptarewellsuitedforLinearAlgebra. 6.1 Vectors Givenavectorx 𝑥$ 𝑥9 𝑥 = ⋮ ∈ 𝑅) 𝑥) Example:Vectors Giventhefollowingvector 1 𝑥= 2 3 >> x=[1; 2; 3] x = 1 2 3 TheTransposeofvectorx: 𝑥 3 = 𝑥$ 𝑥9 ⋯ 𝑥) ∈ 𝑅$-) >> x' ans = 1 2 3 TheLengthofvectorx: Tutorial:LinearAlgebrainLabVIEW 31 𝑥 = LinearAlgebraExamplesusingMathScript 𝑥$9 + 𝑥99 + ⋯ + 𝑥)9 𝑥3𝑥 = Orthogonality: 𝑥 3 𝑦 = 0 6.2 Matrices GivenamatrixA: 𝑎$$ 𝐴= ⋮ 𝑎)$ ⋯ ⋱ ⋯ 𝑎$& ⋮ ∈ 𝑅)-& 𝑎)& 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 1 -2 -3 Tutorial:LinearAlgebrainLabVIEW 32 6.2.2 LinearAlgebraExamplesusingMathScript Diagonal TheDiagonalelementsofmatrixAisthevector 𝑎$$ 𝑎99 𝑑𝑖𝑎𝑔(𝐴) = ⋮ ∈ 𝑅:;<=>(-,&) 𝑎:: Example:Diagonal FindthediagonalelementsofmatrixA: >> diag(A) ans = 0 -3 TheDiagonalmatrixΛisgivenby: 𝜆$ 0 Λ= ⋮ 0 0 𝜆9 ⋮ 0 ⋯ ⋯ ⋱ ⋯ 0 0 ∈ 𝑅)-) ⋮ 𝜆) GiventheIdentitymatrixI: 1 0 ⋯ 0 1 ⋯ 𝐼= ⋮ ⋮ ⋱ 0 0 ⋯ 0 0 ∈ 𝑅)-& ⋮ 1 Example:IdentityMatrix Getthe3x3Identitymatrix: >> eye(3) ans = 1 0 0 6.2.3 0 1 0 0 0 1 Triangular LowerTriangularmatrixL: . 0 𝐿= ⋮ ⋱ . ⋯ 0 0 . Tutorial:LinearAlgebrainLabVIEW 33 LinearAlgebraExamplesusingMathScript UpperTriangularmatrixU: . ⋯ 𝑈= 0 ⋱ 0 0 6.2.4 . ⋮ . MatrixMultiplication Giventhematrices 𝐴 ∈ 𝑅)-& and 𝐵 ∈ 𝑅&-: ,then 𝐶 = 𝐴𝐵 ∈ 𝑅)-: where ) 𝑎UW 𝑏WV 𝑐UV = 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 𝐶 = 𝐴 + 𝐵 ∈ 𝑅)-& Tutorial:LinearAlgebrainLabVIEW 34 LinearAlgebraExamplesusingMathScript 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 9-9 𝑎99 ∈ 𝑅 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(𝐴) Tutorial:LinearAlgebrainLabVIEW 35 LinearAlgebraExamplesusingMathScript 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 9-9 𝑎99 ∈ 𝑅 Theinverse 𝐴I$ isgivenby 𝐴I$ = 1 𝑎99 −𝑎 9$ det(𝐴) −𝑎$9 9-9 𝑎$$ ∈ 𝑅 Example:InverseMatrices Inversematrix: A = 0 1 -2 -3 >> inv(A) ans = -1.5000 -0.5000 1.0000 0 Noticethat: Tutorial:LinearAlgebrainLabVIEW 36 LinearAlgebraExamplesusingMathScript 𝐴𝐴I$ = 𝐴I$ 𝐴 = 𝐼 →ProvethisinMathScript 6.3 Eigenvalues Given 𝐴 ∈ 𝑅)-) ,thentheEigenvaluesisdefinedas: det 𝜆𝐼 − 𝐴 = 0 Example:Eigenvalues FindtheEigenvalues: A = 0 1 -2 -3 >> eig(A) ans = -1 -2 6.4 SolvingLinearEquations Giventhelinearequation 𝐴𝑥 = 𝑏 withthesolution: 𝑥 = 𝐴I$ 𝑏 (AssumingthattheinverseofAexists) Example:SolvingLinearEquations Solvingthefollowingequation: Theequations 𝑥$ + 2𝑥9 = 5 3𝑥$ + 4𝑥9 = 6 maybewritten 𝐴𝑥 = 𝑏 Tutorial:LinearAlgebrainLabVIEW 37 LinearAlgebraExamplesusingMathScript 1 2 𝑥$ 5 = 𝑥 3 4 9 6 where 𝐴= 1 2 3 4 𝑥$ 𝑥= 𝑥 9 𝑏= 5 6 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.Thissyntax canalsobeusedwhentheinverseofAdon’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 LUfactorization LUfactorizationof 𝐴 ∈ 𝑅)-& isgivenby 𝐴 = 𝐿𝑈 where Tutorial:LinearAlgebrainLabVIEW 38 LinearAlgebraExamplesusingMathScript 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) Tutorial:LinearAlgebrainLabVIEW 39 LinearAlgebraExamplesusingMathScript 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 [L,U]=lu(A) Description LUFactorization [L,U,P]=lu(A) [U,S,V] = svd(A) SingularValueDecomposition(SVD) Tutorial:LinearAlgebrainLabVIEW 7 MathScriptNode The“MathScriptNode”offersanintuitivemeansofcombininggraphicalandtextualcode withinLabVIEW.Thefigurebelowshowsthe“MathScriptNode”ontheblockdiagram, representedbythebluerectangle.Using“MathScriptNodes”,youcanenter.mfilescript textdirectlyorimportitfromatextfile. YoucandefinenamedinputsandoutputsontheMathScriptNodebordertospecifythedata totransferbetweenthegraphicalLabVIEWenvironmentandthetextualMathScriptcode. Youcanassociate.mfilescriptvariableswithLabVIEWgraphicalprogramming,bywiring Nodeinputsandoutputs.Thenyoucantransferdatabetween.mfilescriptswithyour graphicalLabVIEWprogramming.Thetextual.mfilescriptscannowaccessfeaturesfrom traditionalLabVIEWgraphicalprogramming. TheMathScriptNodeisavailablefromLabVIEWfromtheFunctionsPalette:Mathematics→ Scripts&Formulas 40 41 MathScriptNode IfyouclickCtrl+HyougethelpabouttheMathScriptNode: Click“Detailedhelp”inordertogetmoreinformationabouttheMathScriptNode. UsetheNIExampleFinderinordertofindexamples: Tutorial:LinearAlgebrainLabVIEW 42 MathScriptNode 7.1 TransferringMathScriptNodesbetween Computers IfascriptinaMathScriptNodecallsauser-definedfunction,LabVIEWusesthedefault searchpathlisttolinkthefunctioncalltothespecified.mfile.Afteryouconfigurethe defaultsearchpathlistandsavetheVIthatcontainstheMathScriptNode,youdonotneed toreconfiguretheMathScriptsearchpathlistwhenyouopentheVIonadifferentcomputer becauseLabVIEWlooksforthe.mfileinthedirectorywherethe.mfilewaslocatedwhen youlastsavedtheVI.However,youmustmaintainthesamerelativepathbetweentheVI andthe.mfile. 7.2 Examples Example:UsingtheMathScriptNode HereisanexampleofhowyouusetheMathScriptNode.Ontheleftborderyouconnect inputvariablestothescript,ontherightborderyouhaveoutputvariables.Right-clickonthe borderandselect“AddInput”or“AddOutput”. Tutorial:LinearAlgebrainLabVIEW 43 MathScriptNode Example:CallingaWindowsDLL: Example:Usingm-filesintheMathScriptNode: UsetheLabVIEWMathScripttocreateam-filescript(oryoumayuseMATLABtocreatethe samescript): Tutorial:LinearAlgebrainLabVIEW 44 MathScriptNode Right-clickontheborderoftheMathScriptNodeandselect“Import”,andthenselectthemfileyouwanttoimportintotheNode. Tutorial:LinearAlgebrainLabVIEW 45 MathScriptNode Right-clickontherightborderandselect“AddOutput”.Thenright-clickontheoutput variableandselect“CreateIndicator”. BlockDiagram: Theresultisasfollows(clicktheRunbutton): Ifyou,e.g.,addthefollowingcommandintheMathScriptNode:plot(x),thefollowingwindow appears: Tutorial:LinearAlgebrainLabVIEW 46 MathScriptNode 7.3 Exercises UsetheMathScriptNodeandtestthesameexamplesyoudidinthepreviouschapter (Chapter6-“LinearAlgebraExamplesusingMathScript”) Tutorial:LinearAlgebrainLabVIEW 8 WhatsNext? 8.1 MyBlog FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/ 8.2 Training ThisTrainingisapartofaserieswithotherTrainingKitsIhavemade,suchas: • • • • • • • • • IntroductiontoLabVIEW DataAcquisitioninLabVIEW ControlandSimulationinLabVIEW LabVIEWMathScript LinearAlgebrainLabVIEW DataloggingandSupervisoryControlinLabVIEW WirelessDataAcquisitioninLabVIEW IntermediateTopicsinLabVIEW AdvancedTopicsinLabVIEW TheseTrainingKitsareavailablefordownloadfrommyblog:http://home.hit.no/~hansha 8.3 MathScriptFunctions IntheHelpsystemthereisdetailedinformationaboutalltheMathScriptfunctionsavailable. InadditiontotheMathScriptRTModulefunctions,differentadd-onmodulesandtoolkits installsadditionalfunctions.TheLabVIEWControlDesignandSimulationModuleand LabVIEWDigitalFilterDesignToolkitinstallsalotsofadditionalfunctions. 47 48 MathScriptNode Tutorial:LinearAlgebrainLabVIEW QuickReference 49 50 Tutorial:LinearAlgebrainLabVIEW QuickReference Hans-PetterHalvorsen,M.Sc. E-mail:[email protected] Blog:http://home.hit.no/~hansha/ UniversityCollegeofSoutheastNorway www.usn.no