UniversityCollegeofSoutheastNorway
LabVIEWMathScript
Hans-PetterHalvorsen,2016.10.31
http://home.hit.no/~hansha
Preface
ThisdocumentexplainsthebasicconceptsofusingLabVIEWMathScript.
FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
WhatisLabVIEW?
LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa
platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational
Instruments.Thegraphicallanguageisnamed"G".
WhatisMATLAB?
MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegrated
environment.MATLABisanabbreviationforMATrixLABoratory,soitiswellsuitedfor
matrixmanipulationandproblemsolvingrelatedtoLinearAlgebra.
MATLABofferslotsofadditionalToolboxesfordifferentareassuchasControlDesign,Image
Processing,DigitalSignalProcessing,etc.
WhatisMathScript?
MathScriptisahigh-level,text-basedprogramminglanguage.MathScriptincludesmore
than800built-infunctionsandthesyntaxissimilartoMATLAB.Youmayalsocreatecustommadem-filelikeyoudoinMATLAB.
MathScriptisanadd-onmoduletoLabVIEWbutyoudon’tneedtoknowLabVIEW
programminginordertouseMathScript.IfyouwanttointegrateMathScriptfunctions
(built-inorcustom-madem-files)aspartofaLabVIEWapplicationandcombinegraphical
andtextualprogramming,youcanworkwiththeMathScriptNode.
InadditiontotheMathScriptbuilt-infunctions,differentadd-onmodulesandtoolkits
installsadditionalfunctions.TheLabVIEWControlDesignandSimulationModuleand
LabVIEWDigitalFilterDesignToolkitinstalllotsofadditionalfunctions. YoucanmoreinformationaboutMathScripthere:
http://www.ni.com/labview/mathscript.htm
ii
HowdoyoustartusingMathScript? YouneedtoinstallLabVIEWandtheLabVIEWMathScriptRTModule.Whennecessary
softwareisinstalled,startMathScriptbyopenLabVIEW:
IntheGettingStartedwindow,selectTools->MathScriptWindow...:
TableofContents
Preface......................................................................................................................................ii
TableofContents.....................................................................................................................iv
1
IntroductiontoLabVIEW...................................................................................................1
1.1
Dataflowprogramming...............................................................................................1
1.2
Graphicalprogramming..............................................................................................1
1.3
Benefits.......................................................................................................................2
1.4
LabVIEWMathScriptRTModule................................................................................2
2
LabVIEWMathScriptRTModule.......................................................................................4
3
LabVIEWMathScript.........................................................................................................5
3.1
Introduction................................................................................................................5
3.2
Help.............................................................................................................................7
3.3
Examples.....................................................................................................................7
3.4
Usefulcommands.....................................................................................................10
CallingfunctionsInMathScript...........................................................................................10
User-DefinedFunctionsInMathScript................................................................................11
Scripts..................................................................................................................................12
3.5
FlowControl.............................................................................................................14
3.5.1
If-elseStatement...............................................................................................14
3.5.2
SwitchandCaseStatement...............................................................................14
3.5.3
Forloop.............................................................................................................15
3.5.4
Whileloop.........................................................................................................15
3.6
Plotting.....................................................................................................................16
iv
v
4
5
TableofContents
LinearAlgebraExamples.................................................................................................18
4.1
Vectors......................................................................................................................18
4.2
Matrices....................................................................................................................19
4.2.1
Transpose..........................................................................................................19
4.2.2
Diagonal.............................................................................................................20
4.2.3
Triangular..........................................................................................................21
4.2.4
MatrixMultiplication.........................................................................................21
4.2.5
MatrixAddition.................................................................................................22
4.2.6
Determinant......................................................................................................22
4.2.7
InverseMatrices................................................................................................23
4.3
Eigenvalues...............................................................................................................24
4.4
SolvingLinearEquations...........................................................................................25
4.5
LUfactorization.........................................................................................................26
4.6
TheSingularValueDecomposition(SVD).................................................................27
4.7
Commands................................................................................................................28
ControlDesignandSimulation........................................................................................29
5.1
State-spacemodelsandTransferfunctions.............................................................29
5.1.1
PID.....................................................................................................................30
5.1.2
State-spacemodel.............................................................................................31
5.1.3
Transferfunction...............................................................................................32
5.1.4
FirstOrderSystems...........................................................................................33
5.1.5
SecondOrderSystems.......................................................................................34
5.1.6
Padé-approximation..........................................................................................36
5.2
FrequencyResponseAnalysis...................................................................................37
5.2.1
BodeDiagram....................................................................................................38
TimeResponse....................................................................................................................41
Tutorial:LabVIEWMathScript
vi
6
7
TableofContents
MathScriptNode.............................................................................................................43
6.1
TransferringMathScriptNodesbetweenComputers...............................................45
6.2
Examples...................................................................................................................45
6.3
Exercises...................................................................................................................49
MATLABScript.................................................................................................................50
AppendixA–MathScriptFunctionsforControlandSimulation............................................51
Tutorial:LabVIEWMathScript
1 IntroductiontoLabVIEW
LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa
platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational
Instruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheApple
Macintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,and
industrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavors
ofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2009,
releasedinAugust2009.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.
LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
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 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
1
2
IntroductiontoLabVIEW 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
andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,
MacOSXandLinuxplatforms.
FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
1.4 LabVIEWMathScriptRTModule
TheLabVIEWMathScriptRTModuleisanadd-onmoduletoLabVIEW.WithLabVIEW
MathScriptRTModuleyoucan:
Tutorial:LabVIEWMathScript
3
•
•
•
•
IntroductiontoLabVIEW Deployyourcustom.mfilestoNIreal-timehardware
ReusemanyofyourscriptscreatedwithTheMathWorks,Inc.MATLAB®softwareand
others
Developyour.mfileswithaninteractivecommand-lineinterface
EmbedyourscriptsintoyourLabVIEWapplicationsusingtheMathScriptNode
Tutorial:LabVIEWMathScript
2 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
4
3 LabVIEWMathScript
3.1 Introduction
Requires:MathScriptRTModule
HowdoyoustartusingMathScript?YouneedtoinstallLabVIEWandtheLabVIEW
MathScriptRTModule.Whennecessarysoftwareisinstalled,startMathScriptbyopen
LabVIEW:
IntheGettingStartedwindow,selectTools->MathScriptWindow...:
5
6
LabVIEWMathScript 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:
Tutorial:LabVIEWMathScript
7
LabVIEWMathScript [EndofExample]
3.2 Help
Youmayalsotypehelpinyourcommandwindow
>>help
Ormorespecific,e.g.,
>>help plot
3.3 Examples
IadviseyoutotestalltheexamplesinthistextinLabVIEWMathScriptinordertoget
familiarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelike
this:
>>
…
Tutorial:LabVIEWMathScript
8
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
Thecodedefinesavariablenamedarray(orassignsanewvaluetoanexistingvariablewith
thenamearray)whichisanarrayconsistingofthevalues1,3,5,7,and9.Thatis,thearray
startsat1(theinitvalue),incrementswitheachstepfromthepreviousvalueby2(the
incrementvalue),andstopsonceitreaches(ortoavoidexceeding)9(theterminatorvalue).
Theincrementvaluecanactuallybeleftoutofthissyntax(alongwithoneofthecolons),to
useadefaultvalueof1.
>> ari = 1:5
Tutorial:LabVIEWMathScript
9
LabVIEWMathScript ari =
1 2 3 4 5
Thecodeassignstothevariablenamedarianarraywiththevalues1,2,3,4,and5,since
thedefaultvalueof1isusedastheincrementer.
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 =
Tutorial:LabVIEWMathScript
10
LabVIEWMathScript 1 1 1
1 1 1
3.4 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
CallingfunctionsInMathScript
MathScriptincludesmorethan800built-infunctionsthatyoucanuse,e.g.,inaprevious
taskyouusedtheplotfunction.
Example:Built-inFunctions
Giventhevector:
>>x=[1 2 5 6 8 9 3]
→Findthemeanvalueofthevectorx.
→Findtheminimumvalueofthevectorx.
→Findthemaximumvalueofthevectorx.
TheMathScriptCodeis:
x=[1 2 5 6 8 9 3]
mean(x)
Tutorial:LabVIEWMathScript
11
LabVIEWMathScript min(x)
max(x)
[EndofExample]
User-DefinedFunctionsInMathScript
MathScriptincludesmorethan800built-infunctionsthatyoucanusebutsometimesyou
needtocreateyourownfunctions.
TodefineyourownfunctioninMathScript,usethefollowingsyntax:
function outputs = function_name(inputs)
% documentation
…
Hereistheprocedureforcreatingaauser-definedfunctioninMathScript:
Tutorial:LabVIEWMathScript
12
LabVIEWMathScript Scripts
AscriptisasequenceofMathScriptcommandsthatyouwanttoperformtoaccomplisha
task.Whenyouhavecreatedthescriptyoumaysaveitasam-fileforlateruse.
YoumayalsohavemultipleScriptWindowsopenatthesametimebyselecting“NewScript
Editor”intheFilemenu:
Tutorial:LabVIEWMathScript
13
LabVIEWMathScript Thisgives:
Tutorial:LabVIEWMathScript
14
LabVIEWMathScript 3.5 FlowControl
ThischapterexplainsthebasicconceptsofflowcontrolinMathScript.
Thetopicsareasfollows:
•
•
•
•
If-elsestatement
Switchandcasestatement
Forloop
Whileloop
3.5.1
If-elseStatement
Theifstatementevaluatesalogicalexpressionandexecutesagroupofstatementswhenthe
expressionistrue.Theoptionalelseifandelsekeywordsprovidefortheexecutionof
alternategroupsofstatements.Anendkeyword,whichmatchestheif,terminatesthelast
groupofstatements.Thegroupsofstatementsaredelineatedbythefourkeywords—no
bracesorbracketsareinvolved.
Example:If-ElseStatement
Testthefollowingcode:
n=5
if n > 2
M = eye(n)
elseif n < 2
M = zeros(n)
else
M = ones(n)
end
[EndofExample]
3.5.2
SwitchandCaseStatement
Theswitchstatementexecutesgroupsofstatementsbasedonthevalueofavariableor
expression.Thekeywordscaseandotherwisedelineatethegroups.Onlythefirstmatching
caseisexecuted.Theremustalwaysbeanendtomatchtheswitch.
Example:SwitchandCaseStatement
Testthefollowingcode:
n=2
switch(n)
Tutorial:LabVIEWMathScript
15
LabVIEWMathScript case 1
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
[EndofExample]
3.5.3
Forloop
Theforlooprepeatsagroupofstatementsafixed,predeterminednumberoftimes.A
matchingenddelineatesthestatements.
Example:ForLoop
Testthefollowingcode:
m=5
for n = 1:m
r(n) = rank(magic(n));
end
r
[EndofExample]
3.5.4
Whileloop
Thewhilelooprepeatsagroupofstatementsanindefinitenumberoftimesundercontrolof
alogicalcondition.Amatchingenddelineatesthestatements.
Example:WhileLoop
Testthefollowingcode:
m=5;
while m > 1
m = m - 1;
zeros(m)
end
[EndofExample]
Tutorial:LabVIEWMathScript
16
LabVIEWMathScript 3.6 Plotting
ThischapterexplainsthebasicconceptsofcreatingplotsinMathScript.
Topics:
•
BasicPlotcommands
Example:Plotting
Functionplotcanbeusedtoproduceagraphfromtwovectorsxandy.Thecode:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
producesthefollowingfigureofthesinefunction:
[EndofExample]
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}')
Tutorial:LabVIEWMathScript
17
LabVIEWMathScript ylabel('{\bfy}')
zlabel('{\bfsinc} ({\bfR})')
hidden off
Thiscodeproducesthefollowing3Dplot:
[EndofExample]
Tutorial:LabVIEWMathScript
4 LinearAlgebraExamples
Requires:MathScriptRTModule
Linearalgebraisabranchofmathematicsconcernedwiththestudyofmatrices,vectors,
vectorspaces(alsocalledlinearspaces),linearmaps(alsocalledlineartransformations),and
systemsoflinearequations.
MathScriptarewellsuitedforLinearAlgebra.
4.1 Vectors
Givenavectorx
𝑥2
𝑥3
𝑥 = ⋮ ∈ 𝑅5 𝑥5
Example:Vectors
Giventhefollowingvector
1
𝑥= 2
3
>> x=[1; 2; 3]
x =
1
2
3
TheTransposeofvectorx:
𝑥 8 = 𝑥2
𝑥3
⋯
>> x'
ans =
1
2
3
[EndofExample]
18
𝑥5 ∈ 𝑅2:5 19
LinearAlgebraExamples TheLengthofvectorx:
𝑥 =
𝑥23 + 𝑥33 + ⋯ + 𝑥53 𝑥8𝑥 =
Orthogonality:
𝑥 8 𝑦 = 0
4.2 Matrices
GivenamatrixA:
𝑎22
𝐴= ⋮
𝑎52
⋯
⋱
⋯
𝑎2<
⋮ ∈ 𝑅5:< 𝑎5<
Example:Matrices
Giventhefollowingmatrix:
𝐴=
0
1
−2 −3
>> A=[0 1;-2 -3]
A =
0
1
-2
-3
[EndofExample]
4.2.1
Transpose
TheTransposeofmatrixA:
𝑎22
𝐴 = ⋮
𝑎2<
8
⋯
⋱
⋯
𝑎52
⋮ ∈ 𝑅<:5 𝑎5<
Example:Transpose
Giventhematrix:
𝐴8 =
0
1
−2 −3
8
=
0 −2
1 −3
Tutorial:LabVIEWMathScript
20
LinearAlgebraExamples >> A'
ans =
0
1
-2
-3
[EndofExample]
4.2.2
Diagonal
TheDiagonalelementsofmatrixAisthevector
𝑎22
𝑎33
𝑑𝑖𝑎𝑔(𝐴) = ⋮ ∈ 𝑅DEFGH(:,<) 𝑎DD
Example:Diagonal
FindthediagonalelementsofmatrixA:
>> diag(A)
ans =
0
-3
[EndofExample]
TheDiagonalmatrixΛisgivenby:
𝜆2
0
Λ=
⋮
0
0
𝜆3
⋮
0
⋯
⋯
⋱
⋯
0
0
∈ 𝑅5:5 ⋮
𝜆5
GiventheIdentitymatrixI:
1 0 ⋯
0 1 ⋯
𝐼=
⋮ ⋮ ⋱
0 0 ⋯
0
0
∈ 𝑅5:< ⋮
1
Example:IdentityMatrix
Getthe3x3Identitymatrix:
>> eye(3)
ans =
1
0
0
Tutorial:LabVIEWMathScript
21
0
0
1
0
LinearAlgebraExamples 0
1
[EndofExample]
4.2.3
Triangular
LowerTriangularmatrixL:
. 0
𝐿= ⋮ ⋱
. ⋯
0
0
.
. ⋯
𝑈= 0 ⋱
0 0
.
⋮
.
UpperTriangularmatrixU:
4.2.4
MatrixMultiplication
Giventhematrices 𝐴 ∈ 𝑅5:< and 𝐵 ∈ 𝑅<:D ,then
𝐶 = 𝐴𝐵 ∈ 𝑅5:D where
5
𝑎RT 𝑏TS 𝑐RS =
TE2
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
[EndofExample]
Tutorial:LabVIEWMathScript
22
Note!
𝐴𝐵 ≠ 𝐵𝐴
𝐴 𝐵𝐶 = 𝐴𝐵 𝐶
𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶
𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵
4.2.5
MatrixAddition
Giventhematrices 𝐴 ∈ 𝑅5:< and 𝐵 ∈ 𝑅5:< ,then
𝐶 = 𝐴 + 𝐵 ∈ 𝑅5:< Example:MatrixAddition
Matrixaddition:
>> A=[0 1;-2 -3]
>> B=[1 0;3 -2]
>> A+B
ans =
1
1
1
-5
[EndofExample]
4.2.6
Determinant
Givenamatrix 𝐴 ∈ 𝑅5:5 ,thentheDeterminantisgiven:
det 𝐴 = 𝐴 Givena2x2matrix
𝑎22
𝐴= 𝑎
32
𝑎23
3:3
𝑎33 ∈ 𝑅 Then
det 𝐴 = 𝐴 = 𝑎22 𝑎33 − 𝑎32 𝑎23 Tutorial:LabVIEWMathScript
LinearAlgebraExamples 23
Example:Determinant
Findthedeterminant:
A =
0
1
-2
-3
>> det(A)
ans =
2
Noticethat
det 𝐴𝐵 = det 𝐴 det 𝐵 and
det 𝐴8 = det(𝐴)
[EndofExample]
Example:Determinant
Determinants:
>> det(A*B)
ans =
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
ans =
2
[EndofExample]
4.2.7
InverseMatrices
Theinverseofaquadraticmatrix 𝐴 ∈ 𝑅5:5 isdefinedby:
𝐴Y2 if
Tutorial:LabVIEWMathScript
LinearAlgebraExamples 24
LinearAlgebraExamples 𝐴𝐴Y2 = 𝐴Y2 𝐴 = 𝐼
Fora2x2matrixwehave:
𝑎22
𝐴= 𝑎
32
𝑎23
3:3
𝑎33 ∈ 𝑅 Theinverse 𝐴Y2 isgivenby
𝐴Y2 =
1
𝑎33
−𝑎
32
det(𝐴)
−𝑎23
3:3
𝑎22 ∈ 𝑅 Example:InverseMatrices
Inversematrix:
A =
0
1
-2
-3
>> inv(A)
ans =
-1.5000
-0.5000
1.0000
0
[EndofExample]
Noticethat:
𝐴𝐴Y2 = 𝐴Y2 𝐴 = 𝐼
→ProvethisinMathScript
4.3 Eigenvalues
Given 𝐴 ∈ 𝑅5:5 ,thentheEigenvaluesisdefinedas:
det 𝜆𝐼 − 𝐴 = 0
Example:Eigenvalues
FindtheEigenvalues:
A =
0
1
-2
-3
>> eig(A)
ans =
-1
-2
Tutorial:LabVIEWMathScript
25
LinearAlgebraExamples [EndofExample]
4.4 SolvingLinearEquations
Giventhelinearequation
𝐴𝑥 = 𝑏
withthesolution:
𝑥 = 𝐴Y2 𝑏
(AssumingthattheinverseofAexists)
Example:SolvingLinearEquations
Solvingthefollowingequation:
Theequations
𝑥2 + 2𝑥3 = 5
3𝑥2 + 4𝑥3 = 6
maybewritten
𝐴𝑥 = 𝑏
1 2 𝑥2
5
=
3 4 𝑥3
6
where
𝐴=
1 2
3 4
𝑥2
𝑥= 𝑥 3
𝑏=
5
6
Thesolutionis:
A =
1
2
3
4
>> b=[5;6]
b =
5
6
>> x=inv(A)*b
Tutorial:LabVIEWMathScript
26
LinearAlgebraExamples x =
-4.0000
4.5000
InMathScriptyoucouldalsowrite“x=A\b”,whichshouldgivethesameanswer.Thissyntax
canalsobeusedwhentheinverseofAdon’texists.
[EndofExample]
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
[EndofExample]
4.5 LUfactorization
LUfactorizationof 𝐴 ∈ 𝑅5:< isgivenby
𝐴 = 𝐿𝑈 where
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
Tutorial:LabVIEWMathScript
27
0
LinearAlgebraExamples 0.6667
[EndofExample]
OrsometimesLUfactorizationof 𝐴 ∈ 𝑅5:< 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
[EndofExample]
4.6 TheSingularValueDecomposition(SVD)
TheSingularvalueDecomposition(SVD)ofthematrix 𝐴 ∈ 𝑅5:< isgivenby
𝐴 = 𝑈𝑆𝑉 8 where
Uisaorthogonalmatrix
Visaorthogonalmatrix
Sisadiagonalsingularmatrix
Tutorial:LabVIEWMathScript
28
LinearAlgebraExamples 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
[EndofExample]
4.7 Commands
Command
[L,U]=lu(A)
Description
LUFactorization
[L,U,P]=lu(A)
[U,S,V] = svd(A)
SingularValueDecomposition(SVD)
Tutorial:LabVIEWMathScript
5 ControlDesignand
Simulation
UsingLabVIEWMathScriptforControlDesignpurposesyouneedtoinstallthe“Control
DesignandSimulationModule”inadditiontothe“MathScriptRTModule”itself.
UsetheControlDesignMathScriptRTModulefunctionstodesign,analyze,andsimulate
linearcontrollermodelsusingatext-basedlanguage.ThefollowingisalistofControlDesign
MathScriptRTModuleclassesoffunctionsandcommandsthatLabVIEWMathScript
supports.
GettinghelpaboutMathScriptfunctionsregardingtheControlDesignToolkit(CDT),type
“helpcdt”intheCommandWindowintheMathScriptenvironment.
Thefollowingfunctionclassesexist:
Wewillgothroughsomeoftheclassesandfunctionindetailbelow:
5.1 State-spacemodelsandTransferfunctions
MathScriptofferslotsoffunctionsfordefiningandmanipulatestate-spacemodelsand
transferfunctions.
29
30
ControlDesignandSimulation Class:contruct
Description:
Usefunctionsintheconstructclasstoconstructlineartime-invariantsystemmodelsandto
convertbetweenmodelforms.
Belowweseethedifferentfunctionsavailableintheconstructclass:
Belowwewillgivesomeexamplesofhowtousethemostimportfunctionsinthisclass.
5.1.1
PID
Currently,theProportional-Integral-Derivative(PID)algorithmisthemostcommoncontrol
algorithmusedinindustry.
InPIDcontrol,youmustspecifyaprocessvariableandasetpoint.Theprocessvariableisthe
systemparameteryouwanttocontrol,suchastemperature,pressure,orflowrate,andthe
setpointisthedesiredvaluefortheparameteryouarecontrolling.
APIDcontrollerdeterminesacontrolleroutputvalue,suchastheheaterpowerorvalve
position.Thecontrollerappliesthecontrolleroutputvaluetothesystem,whichinturn
drivestheprocessvariabletowardtheset-pointvalue.
ThenthePIDcontrollercalculatesthecontrolleraction,u(t):
𝑢(𝑡) = 𝐾b 𝑒 +
1
𝑇d
f
g
𝑒𝑑𝑡 + 𝑇e
𝑑𝑒
𝑑𝑡
Where
𝐾b Controllergain
𝑇d Integraltime
Tutorial:LabVIEWMathScript
31
ControlDesignandSimulation 𝑇e Derivativetime
And 𝑒 istheerror
𝑒 = 𝑆𝑃 − 𝑃𝑉
SP–Setpoint
PV–ProcessVariable
Function:pid
Description: Constructsaproportional-integral-derivative(PID)controllermodelineitherparallel,series,
oracademicform.
Examples:
Kc = 0.5;
Ti = 0.25;
SysOutTF = pid(Kc, Ti, 'academic');
[EndofExample]
5.1.2
State-spacemodel
Astate-spacemodelisjustastructuredformorrepresentationofthedifferentialequations
forasystem.
AlinearState-spacemodel:
𝑥 = 𝐴𝑥 + 𝐵𝑢
𝑦 = 𝐶𝑥 + 𝐷𝑢
wherexisthestatevectoranduistheinputvector.Aiscalledthesystem-matrix,andis
squareinallcases.
Example:
Thedifferentialequations:
Tutorial:LabVIEWMathScript
32
ControlDesignandSimulation 𝑥2 = −2𝑥2 + 6𝑢
𝑥3 = 2𝑥2 Maybewrittenonstate-spaceform:
𝑥2
−2 0 𝑥2
6
=
+
𝑢
𝑥3
2 0 𝑥3
0
Function:ss
Description: Thisfunctionconstructsacontinuousordiscretelinearsystemmodelinstate-spaceform.
Youalsocanusethisfunctiontoconverttransferfunctionandzero-pole-gainmodelsto
state-spaceform.
Examples:
% Creates a state-space model
A = eye(2)
B = [0; 1]
C = B'
SysOutSS = ss(A, B, C)
% Converts a zero-pole-gain model to state-space form
z = 1
p = [1, -1]
k = 1
SysIn = zpk(z, p, k)
SysOutSS = ss(SysIn)
[EndofExample]
5.1.3
Transferfunction
ThetransferfunctionofalinearsystemisdefinedastheratiooftheLaplacetransformof
theoutputvariabletotheLaplacetransformoftheinputvariable.
𝐻 𝑆 =
𝑦(𝑠)
𝑢(𝑠)
Functiontf
Description: Tutorial:LabVIEWMathScript
33
ControlDesignandSimulation Thisfunctioncreatesacontinuousordiscretelinearsystemmodelintransferfunctionform.
Youalsocanusethisfunctiontoconvertzero-pole-gainandstate-spacemodelstotransfer
functionform.
Examples:
>>s = tf('s')
Thisspecifiesthatyouwanttocreatethecontinuoustransferfunctions/1.Afteryouenter
thiscommand,youcanuseLabVIEWMathScriptoperandsonthistransferfunctiontodefine
azero-pole-gainortransferfunctionmodel. SysOutZPK = 4*(s + 2) / (s + 1)
Thisexampleconstructsazero-pole-gainmodelwithagainof4,azeroat-2,andapoleat1.
SysOutTF = (3*(s*s*s) + 2) / (4*(s*s*s*s) + 8)
Thisexampleconstructsthetransferfunctionmodel3s^3+2/4s^4+8.
[EndofExample]
5.1.4
FirstOrderSystems
Thefollowingtransferfunctiondefinesafirstordersystem:
𝐻 𝑠 =
𝐾
𝑇𝑠 + 1
Where
𝐾 isthegain
𝑇 istheTimeconstant
Functionsys_order1
Description: Thisfunctionconstructsthecomponentsofafirst-ordersystemmodelbasedonagain,time
constant,anddelaythatyouspecify.Youcanusethisfunctiontocreateeitherastate-space
modeloratransferfunctionmodel,dependingontheoutputparametersyouspecify.
Tutorial:LabVIEWMathScript
34
ControlDesignandSimulation Inputs:
KSpecifiesthegainmatrix.Kisarealmatrix. tauSpecifiesthetimeconstant,inseconds,whichisthetimerequiredforthemodeloutput
toreach63%ofitsfinalvalue.Thedefaultvalueis0. delaySpecifiestheresponsedelayofthemodel,inseconds.Thedefaultvalueis0.
Examples:
K = 0.5;
tau = 1.5;
SysOutTF = sys_order1(K, tau);
[EndofExample]
5.1.5
SecondOrderSystems
Astandardsecondordertransferfunctionmodelmaybewrittenlikethis:
𝐻 𝑠 =
𝑦(𝑠)
𝐾𝜔g 3
= 3
=
𝑢(𝑠) 𝑠 + 2𝜁𝜔g 𝑠 + 𝜔g 3
𝐾
𝑠
𝜔g
3
𝑠
+ 2𝜁
+1
𝜔g
Where
𝐾 isthegain
𝜁(zetaistherelativedampingfactor
𝜔g [rad/s]istheundampedresonancefrequency.
Functionsys_order2
Description: Thisfunctionconstructsthecomponentsofasecond-ordersystemmodelbasedona
dampingratioandnaturalfrequencyyouspecify.Youcanusethisfunctiontocreateeithera
state-spacemodeloratransferfunctionmodel,dependingontheoutputparametersyou
specify.
Example:
Examplesofhowtousethesys_order2function:
Tutorial:LabVIEWMathScript
35
ControlDesignandSimulation dr = 0.5
wn = 20
[num, den] = sys_order2(wn, dr)
SysTF = tf(num, den)
[A, B, C, D] = sys_order2(wn, dr)
SysSS = ss(A, B, C, D)
[EndofExample]
Class:connect
Description:
Usemembersoftheconnectclasstoconnectsystemsmodelstogetherinvarious
configurations.
Belowweseethedifferentfunctionsavailableintheconnectclass:
Functionseries
Description: ThisfunctionconnectstwosystemmodelsinseriestoproduceamodelSysSerwithinput
andoutputconnectionsyouspecify.Theinputmodelsmustbeeithercontinuousmodelsor
discretemodelswithidenticalsamplingtimes.
Example:
Hereisanexampleofhowtousetheseriesfunction.
SysIn_1 = tf([1, 1], [1 -1, 3])
SysIn_2 = zpk([1], [1, -1], 1)
SysSer = series(SysIn_1, SysIn_2)
[EndofExample]
Class:convert
Tutorial:LabVIEWMathScript
36
ControlDesignandSimulation Description:
Usemembersoftheconvertclasstoconvertacontinuoussystemmodeltoadiscrete
model,convertadiscretemodeltoacontinuousmodel,andresampleadiscretemodel.You
alsocanusemembersofthisclasstoincorporatedelaysintoasystemmodel.
Belowweseethedifferentfunctionsavailableintheconvertclass:
5.1.6
Padé-approximation
TheTransferfunctionofatime-delayis:
𝐻 𝑠 = 𝑒 Ymn Insomesituationsitisnecessarytosubstitute 𝑒 Ymn withanapproximation,e.g.,thePadéapproximation:
𝑒
Ymn
1 − 𝑘2 𝑠 + 𝑘3 𝑠 3 + ⋯± 𝑘5 𝑠 5
≈
1 + 𝑘2 𝑠 + 𝑘3 𝑠 3 + ⋯ + 𝑘5 𝑠 5
Function:pade
Description: ThisfunctionincorporatestimedelaysintoasystemmodelusingthePadeapproximation
method,whichconvertsallresiduals.Youmustspecifythedelayusingthesetfunction.You
alsocanusethisfunctiontocalculatecoefficientsofnumeratoranddenominator
polynomialfunctionswithaspecifieddelay.
Example:
Examplesofhowtousethepadefunction:
SysCon = zpk(1, 3.2, 6)
SysCon = set(SysCon, 'inputdelay', 6, 'outputdelay', 1.1)
SysDel = pade(SysCon, 2)
Tutorial:LabVIEWMathScript
37
ControlDesignandSimulation delay = 1.2
order = 3
[num, den] = pade(delay, order)
[EndofExample]
5.2 FrequencyResponseAnalysis
Thefrequencyresponseofasystemisafrequencydependentfunctionwhichexpresseshow
asinusoidalsignalofagivenfrequencyonthesysteminputistransferredthroughthe
system.Eachfrequencycomponentisasinusoidalsignalhavingacertainamplitudeanda
certainfrequency.
Thefrequencyresponseisanimportanttoolforanalysisanddesignofsignalfiltersandfor
analysisanddesignofcontrolsystems.
Thefrequencyresponsecanfoundexperimentallyorfromatransferfunctionmodel.
Thefrequencyresponseofasystemisdefinedasthesteady-stateresponseofthesystemto
asinusoidalinputsignal.Whenthesystemisinsteady-stateitdiffersfromtheinputsignal
onlyinamplitude(A)andphaseangle(ω). Ifwehavetheinputsignal:
𝑢 𝑡 = 𝑈𝑠𝑖𝑛𝜔𝑡
Thesteady-stateoutputsignalwillbe:
𝑦 𝑡 = 𝑈𝐴sin(𝜔𝑡 + 𝜙)
Aand 𝜙 isafunctionofthefrequencyωsowemaywrite 𝐴 = 𝐴 𝜔 , 𝜙 = 𝜙(𝜔)
Foratransferfunction
𝐻 𝑆 =
𝑦(𝑠)
𝑢(𝑠)
Wehave:
𝐴 𝜔 = 𝐻(𝑗𝜔) 𝜙 𝜔 = ∠𝐻(𝑗𝜔) Where 𝐻(𝑗𝜔) isthefrequencyresponseofthesystem,i.e.,wemayfindthefrequency
responsebysetting 𝑠 = 𝑗𝜔 inthetransferfunction.
Tutorial:LabVIEWMathScript
38
5.2.1
ControlDesignandSimulation BodeDiagram
Bodediagramsareusefulinfrequencyresponseanalysis.TheBodediagramconsistsof2
diagrams,theBodemagnitudediagram, 𝐴(𝜔) andtheBodephasediagram, 𝜙(𝜔).
The 𝐴(𝜔)-axisisindecibel(dB)
Wherethedecibelvalueofxiscalculatedas: 𝑥 𝑑𝐵 = 20𝑙𝑜𝑔2g 𝑥
The 𝜙(𝜔)-axisisindegrees(notradians)
Function:bode
Description: ThisfunctioncreatestheBodemagnitudeandBodephaseplotsofasystemmodel.Youalso
canusethisfunctiontoreturnthemagnitudeandphasevaluesofamodelatfrequencies
youspecify.Ifyoudonotspecifyanoutput,thisfunctioncreatesaplot.
Examples:
Wehavethefollowingtransferfunction
𝐻 𝑠 =
𝑦(𝑠)
1
=
𝑢(𝑠) 𝑠 + 1
WewanttoplottheBodediagramforthistransferfunction:
InMathScriptwecouldwrite:
Tutorial:LabVIEWMathScript
39
ControlDesignandSimulation num=[1];
den=[1,1];
H1=tf(num,den)
bode(H1)
[EndofExample]
Function:margin
Description: Thisfunctioncalculatesand/orplotsthesmallestgainandphasemarginsofasingle-input
single-output(SISO)systemmodel. Thegainmarginindicateswherethefrequencyresponsecrossesat0decibels(“crossover
frequency”, 𝜔b ). 𝐻(𝑗𝑤b ) 𝜔b isalsothebandwidthofthesystem
Thephasemarginindicateswherethefrequencyresponsecrosses-180degrees(“crossover
frequency”, 𝜔2ƒg ).
∠𝐻(𝑗𝑤2ƒg )
Examples:
Thefollowingexampleillustratestheuseofthemarginfunction.
num = [1]
den = [1, 5, 6]
H = tf(num, den)
margin(H)
[EndofExample]
Example:
Giventhefollowingsystem:
𝐻 𝑆 =
1
𝑠 𝑠+1 3
Tutorial:LabVIEWMathScript
40
ControlDesignandSimulation WewanttoplottheBodediagramandfindthecrossover-frequenciesforthesystemusing
MathScript.
Weusethefollowingfunctions:tf,bode,marginsandmargin.
•
•
•
•
•
gmfisthegainmarginfrequencies,inradians/second.Againmarginfrequency
indicateswherethemodelphasecrosses-180degrees. gmReturnsthegainmarginsofthesystem. pmfReturnsthephasemarginfrequencies,inradians/second.Aphasemargin
frequencyindicateswherethemodelmagnitudecrosses0decibels. pmReturnsthephasemarginsofthesystem.
Weget:
BelowweseetheBodediagramwiththecrossover-frequencyandthegainmarginand
phasemarginforthesystemplottedin:
Tutorial:LabVIEWMathScript
41
ControlDesignandSimulation [EndofExample]
TimeResponse
Class:timeresp
Description:
Usemembersofthetimerespclasstocreategenericlinearsimulationsandtimedomain
plotsforstepinputs,impulseinputs,andinitialconditionresponses.
Belowweseethedifferentfunctionsavailableinthetimerespclass:
Function:step
Description: Tutorial:LabVIEWMathScript
42
ControlDesignandSimulation Thisfunctioncreatesastepresponseplotofthesystemmodel.Youalsocanusethis
functiontoreturnthestepresponseofthemodeloutputs.Ifthemodelisinstate-space
form,youalsocanusethisfunctiontoreturnthestepresponseofthemodelstates.This
functionassumestheinitialmodelstatesarezero.Ifyoudonotspecifyanoutput,this
functioncreatesaplot.
Example:
Giventhefollowingsystem:
𝐻 𝑠 =
𝑠3
𝑠+1
−𝑠+3
Wewillplotthetimeresponseforthetransferfunctionusingthestepfunction
Theresultisasfollows:
TheMathScriptcode:
H = tf([1, 1], [1, -1, 3])
step(H)
[EndofExample]
Tutorial:LabVIEWMathScript
6 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
43
44
MathScriptNode IfyouclickCtrl+HyougethelpabouttheMathScriptNode:
Click“Detailedhelp”inordertogetmoreinformationabouttheMathScriptNode.
UsetheNIExampleFinderinordertofindexamples:
Tutorial:LabVIEWMathScript
45
MathScriptNode 6.1 TransferringMathScriptNodesbetween
Computers
IfascriptinaMathScriptNodecallsauser-definedfunction,LabVIEWusesthedefault
searchpathlisttolinkthefunctioncalltothespecified.mfile.Afteryouconfigurethe
defaultsearchpathlistandsavetheVIthatcontainstheMathScriptNode,youdonotneed
toreconfiguretheMathScriptsearchpathlistwhenyouopentheVIonadifferentcomputer
becauseLabVIEWlooksforthe.mfileinthedirectorywherethe.mfilewaslocatedwhen
youlastsavedtheVI.However,youmustmaintainthesamerelativepathbetweentheVI
andthe.mfile.
6.2 Examples
Example:UsingtheMathScriptNode
HereisanexampleofhowyouusetheMathScriptNode.Ontheleftborderyouconnect
inputvariablestothescript,ontherightborderyouhaveoutputvariables.Right-clickonthe
borderandselect“AddInput”or“AddOutput”.
Tutorial:LabVIEWMathScript
46
MathScriptNode [EndofExample]
Example:CallingaWindowsDLL:
[EndofExample]
Example:Usingm-filesintheMathScriptNode:
UsetheLabVIEWMathScripttocreateam-filescript(oryoumayuseMATLABtocreatethe
samescript):
Tutorial:LabVIEWMathScript
47
MathScriptNode Right-clickontheborderoftheMathScriptNodeandselect“Import”,andthenselectthemfileyouwanttoimportintotheNode.
Tutorial:LabVIEWMathScript
48
MathScriptNode Right-clickontherightborderandselect“AddOutput”.Thenright-clickontheoutput
variableandselect“CreateIndicator”.
BlockDiagram:
Theresultisasfollows(clicktheRunbutton):
Ifyou,e.g.,addthefollowingcommandintheMathScriptNode:plot(x),thefollowingwindow
appears:
[EndofExample]
Tutorial:LabVIEWMathScript
49
MathScriptNode 6.3 Exercises
UsetheMathScriptNodeandtestthesameexamplesyoudidinapreviouschapter(Chapter
4-“LinearAlgebraExamples”).
Tutorial:LabVIEWMathScript
7 MATLABScript
TheMATLABScriptcallstheMATLABsoftwaretoexecutescripts.Youmusthavealicensed
copyoftheMATLABsoftwareversion6.5orlaterinstalledonyourcomputertouseMATLAB
scriptnodesbecausethescriptnodesinvoketheMATLABsoftwarescriptservertoexecute
scriptswrittenintheMATLABlanguagesyntax.BecauseLabVIEWusesActiveXtechnologyto
implementMATLABscriptnodes,theyareavailableonlyonWindows.
50
AppendixA–MathScript
FunctionsforControland
Simulation
HerearesomedescriptionsforthemostusedMathScriptfunctionsusedinthisLabWork.
Function
Description
Example
plot
Generatesaplot.plot(y)plotsthecolumnsofyagainstthe
indexesofthecolumns.
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
tf
Createssystemmodelintransferfunctionform.Youalsocan
usethisfunctiontostate-spacemodelstotransferfunction
form.
>num=[1];
Returnsthelocationsoftheclosed-looppolesofasystem
model.
>num=[1]
poles
>den=[1, 1, 1];
>H = tf(num, den)
>den=[1,1]
>H=tf(num,den)
>poles(H)
tfinfo
Returnsinformationaboutatransferfunctionsystemmodel.
>[num, den, delay, Ts] =
tfinfo(SysInTF)
step
Createsastepresponseplotofthesystemmodel.Youalso
canusethisfunctiontoreturnthestepresponseofthemodel
outputs.Ifthemodelisinstate-spaceform,youalsocanuse
thisfunctiontoreturnthestepresponseofthemodelstates.
Thisfunctionassumestheinitialmodelstatesarezero.Ifyou
donotspecifyanoutput,thisfunctioncreatesaplot.
>num=[1,1];
Createsthelinearsimulationplotofasystemmodel.This
functioncalculatestheoutputofasystemmodelwhenaset
ofinputsexcitethemodel,usingdiscretesimulation.Ifyoudo
notspecifyanoutput,thisfunctioncreatesaplot.
>t = [0:0.1:10]
Constructsthecomponentsofafirst-ordersystemmodel
basedonagain,timeconstant,anddelaythatyouspecify.
Youcanusethisfunctiontocreateeitherastate-spacemodel
oratransferfunctionmodel,dependingontheoutput
parametersyouspecify.
>K = 1;
Constructsthecomponentsofasecond-ordersystemmodel
basedonadampingratioandnaturalfrequencyyouspecify.
Youcanusethisfunctiontocreateeitherastate-spacemodel
>dr = 0.5
lsim
Sys_order1
Sys_order2
51
>den=[1,-1,3];
>H=tf(num,den);
>t=[0:0.01:10];
>step(H,t);
>u = sin(0.1*pi*t)'
>lsim(SysIn, u, t)
>tau = 1;
>H = sys_order1(K, tau)
>wn = 20
>[num, den] = sys_order2(wn, dr)
52
Error!Referencesourcenotfound. oratransferfunctionmodel,dependingontheoutput
parametersyouspecify.
>SysTF = tf(num, den)
>[A, B, C, D] = sys_order2(wn,
dr)
>SysSS = ss(A, B, C, D)
damp
Returnsthedampingratiosandnaturalfrequenciesofthe
polesofasystemmodel.
>[dr, wn, p] = damp(SysIn)
pid
Constructsaproportional-integral-derivative(PID)controller
modelineitherparallel,series,oracademicform.Refertothe
LabVIEWControlDesignUserManualforinformationabout
thesethreeforms. >Kc = 0.5;
Computestheconvolutionoftwovectorsormatrices.
>C1 = [1, 2, 3];
conv
>Ti = 0.25;
>SysOutTF = pid(Kc, Ti,
'academic');
>C2 = [3, 4];
>C = conv(C1, C2)
series
Connectstwosystemmodelsinseriestoproduceamodel
SysSerwithinputandoutputconnectionsyouspecify
>Hseries = series(H1,H2)
feedback
Connectstwosystemmodelstogethertoproduceaclosedloopmodelusingnegativeorpositivefeedbackconnections
>SysClosed = feedback(SysIn_1,
SysIn_2)
ss
Constructsamodelinstate-spaceform.Youalsocanusethis
functiontoconverttransferfunctionmodelstostate-space
form.
>A = eye(2)
>B = [0; 1]
>C = B'
>SysOutSS = ss(A, B, C)
ssinfo
Returnsinformationaboutastate-spacesystemmodel.
>A = [1, 1; -1, 2]
>B = [1, 2]'
>C = [2, 1]
>D = 0
>SysInSS = ss(A, B, C, D)
>[A, B, C, D, Ts] =
ssinfo(SysInSS)
pade
IncorporatestimedelaysintoasystemmodelusingthePade
approximationmethod,whichconvertsallresiduals.Youmust
specifythedelayusingthesetfunction.Youalsocanusethis
functiontocalculatecoefficientsofnumeratorand
denominatorpolynomialfunctionswithaspecifieddelay.
>[num, den] = pade(delay, order)
bode
CreatestheBodemagnitudeandBodephaseplotsofa
systemmodel.Youalsocanusethisfunctiontoreturnthe
magnitudeandphasevaluesofamodelatfrequenciesyou
specify.Ifyoudonotspecifyanoutput,thisfunctioncreatesa
plot.
>num=[4];
CreatestheBodemagnitudeplotofasystemmodel.Ifyoudo
notspecifyanoutput,thisfunctioncreatesaplot.
>[mag, wout] = bodemag(SysIn)
bodemag
>[A, B, C, D] = pade(delay,
order)
>den=[2, 1];
>H = tf(num, den)
>bode(H)
>[mag, wout] = bodemag(SysIn,
[wmin wmax])
>[mag, wout] = bodemag(SysIn,
wlist)
margin
Calculatesand/orplotsthesmallestgainandphasemarginsof
asingle-inputsingle-output(SISO)systemmodel.Thegain
marginindicateswherethefrequencyresponsecrossesat0
decibels.Thephasemarginindicateswherethefrequency
responsecrosses-180degrees.Usethemarginsfunctionto
returnallgainandphasemarginsofaSISOmodel.
Tutorial:LabVIEWMathScript
>num = [1]
>den = [1, 5, 6]
>H = tf(num, den)
margin(H)
53
margins
Error!Referencesourcenotfound. Calculatesallgainandphasemarginsofasingle-inputsingleoutput(SISO)systemmodel.Thegainmarginsindicatewhere
thefrequencyresponsecrossesat0decibels.Thephase
marginsindicatewherethefrequencyresponsecrosses-180
degrees.Usethemarginfunctiontoreturnonlythesmallest
gainandphasemarginsofaSISOmodel.
>[gmf, gm, pmf, pm] = margins(H)
Formoredetailsaboutthesefunctions,type“helpcdt”togetanoverviewofallthe
functionsusedforControlDesignandSimulation.Fordetailedhelpaboutonespecific
function,type“help<function_name>”.
Plotsfunctions:Herearesomeusefulfunctionsforcreatingplots:plot,figure,subplot,grid,
axis,title,xlabel,ylabel,semilogx–formoreinformationabouttheplotsfunction,type
“helpplots”.
Tutorial:LabVIEWMathScript
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no
© Copyright 2026 Paperzz