Professional Documents
Culture Documents
LabVIEW Mathscript
ALabVIEW toolforexecutingtextualmathematical commands Matrixandvectorbasedcalculations(linearalgebra) Visualizationofdatainplots Runningscriptscontaininganumberofcommandswritten inafile Alargenumberofmathematicalfunctions.MathScript commandareequaltoMATLABcommands(some MATLABcommandsmaynot beimplemented).
LabVIEW Mathscript
MathScript canbeusedintwoways: InaMathScript node whichappearsasaframe insidetheBlockdiagramofaVI(availableonthe Functions/Mathematics/Scripts&Formulas palette.) InaMathScript window asadesktop mathematicaltoolindependentofLabVIEW
To =
K
1 3 A + B ln (R ) + C [ln (R )]
oK
oC
=T
+ 273.15
Output Window
where executed commands and numerical results are shown.
Workspace window
Command Window
LearningtheMathScript language
Startup OpentheMathScript window(menuTools/MathScript Window).
LearningtheMathScript language
1+2 Theresultis3 Toadd4toans: ans+4
ans nowgetsvalue7
LearningtheMathScript language
Recallingpreviouscommands Torecallpreviouscommands,presstheArrowUp buttononthekeyboardasmanytimesas needed. Torecallapreviouscommandstartingwith certaincharacters,typethesecharacters followedbypressingtheArrowDownbuttonon thekeyboard.Tryrecallingtheprevious command(s)beginningwiththeacharacter:
LearningtheMathScript language
Casesensitivity MathScript iscasesensitive:
Help Aboveyouusedthehelpcommand.Itcommand displaysinformationaboutaknowncommand, typicallyincludinganexample.Tryhelpsin
NumberFormats
Theformatcommandisusedtoselectbetweendifferent formatsoftheoutput,cf.theinformationabouttheformat commandthatyousawabove.Trythefollowingcommands: formatshort,100*pi (Comment:5digits,exceptpossible trailingzeros,areshown.) formatlong,100*pi (16digits.) formatshorte,100*pi (5digitsandatermshowingthe exponentsof10) formatlonge,100*pi (16digitsandatermshowingthe exponentsof10) Inmostcasesformatshortisok.Thisisalsothedefault format.Toresettoformatshort: formatshort
NumberFormats
Youcanenternumbersinvariousways:
x1=0.1 x2=1e1 x3=2e2 x4=2*10^(2) x5=exp(1) (thenaturalbase,e=e1 =2.7183) x6=1+2i (acomplexnumber)
AllvariablesgeneratedinaMathScript session(asessionlasts betweenlaunchingandquittingMathScript)aresavedinthe MathScript Workspace.Youcanseethecontentsofthe WorkspaceusingthemenuTools/Workspace/Variables (tab).Alternatively,youcanusethewhocommand:who YoucandeleteavariablefromtheWorkspace: clearx6 MathScript functionsarepolymorphic,i.e.theytypicallytake bothscalarsandvectors(arrays)asarguments.Asan example,thefollowingtwocommandscalculatethesquare rootofthescalar2andthesquarerootofeachofthe elementsofthevectorofintegersfrom0to5,respectively: sqrt(2) sqrt([0,1,2,3,4,5]) Whentheargumentisavectorasinthiscase,thecalculation issaidtobevectorized.
Matricesandvectors
ThematrixisthebasicdataelementinMathScript.Amatrixhavingonly oneroworonelinearefrequentlydenotedvector.Belowareexamplesof creatingandmanipulatingmatrices(andvectors). Tocreateamatrix,usecommatoseparatetheelementsofarowand semicolontoseparatecolumns.Forexample,tocreateamatrixhaving numbers1and2inthefirstrowand3and4inthesecondrow: A=[1,2;3,4] withtheresult A= 12 34 Totransposeamatrixusetheapostrophe: B=A' Tocreatearowvectorfromsay0to4withincrement1: R1=[0:4]
Matricesandvectors
Tocreatearowvector fromsay0to4withincrement0.5: R2=[0:0.5:4] Tocreateacolumnvector fromsay0to4withincrement1: R3=[0:4]' Youcancreatematricesbycombiningvectors (ormatrices): C1=[1,2,3]';C2=[4,5,6]';M=[C1,C2] Herearesomespecialmatrices: Youcanaddress anelementinamatrixusingthestandard(rownumber,column number)indexing.Note:Theelementindexesstartswithone,notzero. (In LabVIEW,arrayindexesstartswithzero....)Forexample(assumingmatrix A=[1,2;3,4]isstillintheWorkspace),toaddressthe(2,1)elementofAandassign thevalueofthatelementtothevariablew: w=A(2,1) withresultw=3. Youcanaddressonewholeroworcolumnusingthe:(colon)operator.For example, C2=A(2,:) withresultC2=[3,4](displayedalittledifferentintheOutput window,though).
Elementbyelementcalculations
Elementbyelement calculationsareexecuted usingthedotoperatortogetherwiththe mathematicaloperator.Hereisanexampleof calculatingtheproductofeachofthe elementsintwovectors: [1,2,3].*[4,5,6] withresult[41018].
Scripts
CreateascriptintheScripteditor(whichisontheScripttab inthe Workspacewindow(anewScripteditorcanopenedviathemenu File/NewScriptEditor)ofnamescript1.mwiththefollowing contents: a=1; b=2; c=a+b Savethescriptinanyfolderyouwant. RunthescriptbyclickingtheRunbutton.Allthecommandsinthe scriptareexecutedfromtoptobottomasiftheywereenteredat thecommandline. Youshouldmakeitahabittousescriptsforallyourwork.Inthis wayyousaveyourwork,andyoucanautomateyourtasks.
Plotting
Youcanplotdatausingtheplotcommand(severaladditionplotting commandsareavailable,too).Hereisanexample: Generateavectortofassumedtimevaluesfrom0to100with increment0.1: t=[0:.1:100]'; Generateavectorxasafunctionoft: x=1+0.02*t; Generateavectoryasafunctionoft: y=sin(0.2*t); OpenFigureno1: figure(1) Plotsxverus t,andyversust,inthesamegraph: plot(t,x,t,y)
Plotting
The resulting plot is shown in the figure below.
Plotting
Probablyyouwanttoaddlabels,annotations,changelinecoloretc.Thiscanbe doneusingmenusinthePlotwindow.Thisisstraightforward,so theoptionsare notdescribedhere. Asanalternativetosettinglabelsetc.viamenusinthePlotwindow,thesecanbe setusingcommands.Belowisanexample,whichshouldbeselfexplaining, howevernotehowtheattributestoeachcurveintheplotisgiven,seetheplot() lineinthecodebelow.
t=[0:.1:100]'; x=1+0.02*t; y=sin(0.2*t); figure(1) plot(t,x,'r',t,y,'b') %x(t)indashedred.y(t)insolidblue. xmin=0;xmax=100;ymin=2;ymax=2; axis([xmin xmax ymin ymax]) grid xlabel('t [sec]') ylabel('x (red,dashed)og y(blue,solid)[Volt]') title('Data fromExperiment1')
Plotting
Plottingasinewave
Run
Plot
t=[0:.1:100]';
Sc
x=-1+0.02*t;
rip t
y=sin(0.2*t);
Ed
ito r
figure(1) plot(t,y,'b-') %x(t) in dashed red. y(t) in solid blue. xmin=0;xmax=100;ymin=-2;ymax=2; axis([xmin xmax ymin ymax]) grid xlabel('t [sec]') ylabel('x (red, dashed) og y (blue, solid) [Volt]') title('Data from Experiment 1')
Definingandsimulatingastransfer function
s=tf('s');%DefinesstobetheLaplace variableusedintransferfunctions K=1;T=1;%Gainandtimeconstant H1=tf(K/(T*s+1));%CreatesHasatransferfunction delay=1;%Timedelay H2=set(H1,'inputdelay',delay);%DefinesH2asH1butwithtimedelay figure(1)%Plotofsimulatedresponsesshownnextslide step(H1,H2)%Simulateswithunitstepasinput,andplotsresponses.
Definingandsimulatingas transferfunction
Calculatingandplottingfrequency responseinaBodeplot
s=tf('s');%DefinesstobetheLaplace variableusedintransferfunctions K=1;T=1;%Gainandtimeconstant H1=tf(K/(T*s+1));%CreatesH1asatransferfunction w_min=0.1;%Minfreqinrad/s w_max=10;%Maxfreqinrad/s [mag,phase,w_out]=bode(H1,[w_min,w_max]);%Calculatesfrequencyresponse figure(1) semilogx(w_out,20*log10(mag)),grid,xlabel('log w[rad/s]'),ylabel('dB')%Plots frequency response figure(2) plot(log10(w_out),20*log10(mag)),grid,xlabel('log w[rad/s]'),ylabel('dB')%Plots frequency response figure(3) plot(w_out,20*log10(mag)),grid,xlabel('w [rad/s]'),ylabel('dB')%Plots frequencyresponse
figure(1)
figure(2)
figure(3)
Frequencyresponseanalysisand simulationoffeedback(control)systems
Thenextscriptshowshowyoucananalyzeacontrolsystem. Inthisexample,theprocesstobecontrollerisatime constantsysteminserieswithatimedelay.Thesensormodel isjustagain.ThecontrollerisaPIcontroller. Thetimedelayisapproximatedwitharationaltransfer function(onthenormalnumeratordenominatorform).This isnecessarywhenyouwanttocalculatethetrackingtransfer functionandthesensitivitytransferfunctionautomatically usingthefeedback function.Thetimedelayapproximationis implementedwiththepade function(Pad approximation). First,themodelsaredefinedusingthetf function.Thetime delayisapproximatedusingthepade function.
Frequencyresponseanalysisand simulationoffeedback(control)systems
Thecontrolsystemissimulatedusingthestep function. Thestabilitymarginsandcorrespondingcrossover frequenciesarecalculatedusingthemargin function. Thecontrolsystemtransferfunctions namelytheloop transferfunction,trackingtransferfuntion andthesensitivity transferfunction arecalculatedusingtheseries function andthefeedback function. ThesetransferfunctionsareplottedinaBodediagramusing thebode function. Althoughthesysteminthisexampleisacontinuoustime system,discretetimesystemscanbeanalysed inthesame way.(Withadiscretetimesystem,noPadapproximationis necessarybecausetimedelayscanbepreciselyrepresented inthemodel.)
TheScript
s=tf('s');%DefinesstobetheLaplace variableusedintransfer functions %Definingtheprocesstransferfunction: K=1;T=1;Tdelay=0.2;%Processparameters padeorder=5;%OrderofPadeapproximationoftimedelay. Order5isusuallyok. P1=set(tf(K/(T*s+1)),'inputdelay',Tdelay);%Includingtime delayinprocesstransferfunction P=pade(P1,padeorder);%Derivingprocesstransferfunction withPadeapproxoftimedelay %Definingsensortransferfunction: Km=1;S=tf(Km);%Definingsensortransferfunction(justa gaininthisexample)
ContinueScript
%Definingcontrollertransferfunction: Kp=2.5;Ti=0.6;C=Kp+Kp/(Ti*s);%PIcontrollertransfer function %Calculatingcontrolsystemtransferfunctions: L=series(C,series(P,S));%Calculatinglooptranfer function M=feedback(L,1);%Calculatingtrackingtransferfunction N=1M;%Calculatingsensitivitytransferfunction %Analysis: figure(1) step(M),grid%Simulatingstepresponseforcontrolsystem (trackingtransferfunction)
ContinueScript
%Calcutating stabilitymarginsandcrossoverfrequencies: [gain_margin,phase_margin,gm_freq,pm_freq]=margin(L) %Note:HelpmargininLabVIEW showserroneously parametersinotherorderthanabove. figure(2) margin(L),grid%PlottingLandstabilitymarginsandcrossover frequenciesinBodediagram figure(3) bodemag(L,M,N),grid%Plotsmaginitude ofL,M,andNin Bodediagram