Home

Tutorial: LabVIEW MathScript

image

Contents

1. Function Description Example plot Generates a plot plot y plots the columns of y against the gt X 0 0 01 1 gt Y X X indexes of the columns gt plot x Y tf Creates system model in transfer function form You also can gt num 1 use this function to state space models to transfer function gt den 1 1 1 form gt H tf num den poles Returns the locations of the closed loop poles of a system gt num 1 model gt den 1 1 gt H tf num den gt poles H tfinfo Returns information about a transfer function system model gt num den delay Ts tfinfo SysInTF step Creates a step response plot of the system model You also can gt num 1 1 use this function to return the step response of the model gt den 1 1 3 outputs If the model is in state space form you also can use this gt H t num den function to return the step response of the model states This gt t 0 0 01 10 function assumes the initial model states are zero If you do not gt step H t specify an output this function creates a plot Isim Creates the linear simulation plot of a system model This gt t 0 0 1 10 function calculates the output of a system model when a set of gt u sin 0 1 pi t inputs excite the model using discrete simulation If you do not gt 1sim SysIn u t specify an output this function creates a plot Sys_order1 Constructs the components of a first order system model based
2. StructuresfPalette Clear Script Clear Script Breakpoints Properties Tutorial LabVIEW MathScript 47 MathScript Node Right click on the right border and select Add Output Then right click on the output variable and select Create Indicator Block Diagram A 1 2 3 4 b 5 6 x inv A b The result is as follows click the Run button If you e g add the following command in the MathScript Node plot x the following window appears File Items Tools Help Graph 5 End of Example Tutorial LabVIEW MathScript 48 MathScript Node 6 3 Exercises Use the MathScript Node and test the same examples you did in the previous chapter Chapter 4 Linear Algebra Examples Tutorial LabVIEW MathScript 7MATLAB Script The MATLAB Script calls the MATLAB software to execute scripts You must have a licensed copy of the MATLAB software version 6 5 or later installed on your computer to use MATLAB script nodes because the script nodes invoke the MATLAB software script server to execute scripts written in the MATLAB language syntax Because LabVIEW uses ActiveX technology to implement MATLAB script nodes they are available only on Windows Script Nodes ES Even LJ MATLAB script 49 Appendix A MathScript Functions for Control and Simulation Here are some descriptions for the most used MathScript functions used in this Lab Work
3. End of Example The Length of vector x 17 18 Linear Algebra Examples llxll YxTx x2 4x2 x2 Orthogonality xt y 0 4 2 Matrices Given a matrix A 41414 Aim A 2 i e R ani Anm Example Matrices Given the following matrix _70 1 a pe ke ER ONE 3 A 0 1 2 3 End of Example 4 2 1 Transpose The Transpose of matrix A Qi On AT pmxn Aim Anm Example Transpose Given the matrix T ar SS AU ans Tutorial LabVIEW MathScript 19 Linear Algebra Examples 11 E End of Example 4 2 2 Diagonal The Diagonal elements of matrix A is the vector A11 a diag A e RP min om App Example Diagonal Find the diagonal elements of matrix A gt gt diag A ans 0 3 End of Example The Diagonal matrix is given by A 0 0 A e Rm 0 0 An Given the Identity matrix 1 0 0 fa 010 prm 0 0 1 Example Identity Matrix Get the 3x3 Identity matrix gt gt eye 3 ans 1 0 0 0 1 0 0 0 1 Tutorial LabVIEW MathScript 20 Linear Algebra Examples End of Example 42 3 Triangular Lower Triangular matrix L Upper Triangular matrix U is 424 Matrix Multiplication Given the matrices A R and B RYWP then C AB e R P where n Cik gt aj dix l 1 Example Matrix Multiplication Matrix multiplication A O SN A 0 1
4. 2 3 gt gt Bali 093 2 B 1 0 3 2 gt gt A B ans 3 2 11 6 End of Example Note Tutorial LabVIEW MathScript 21 AB BA A BC AB C A B C AC BC C A B CA CB 4 2 5 Matrix Addition Given the matrices A R and B R then C A Be RUM Example Matrix Addition Matrix addition gt gt A 0 Asa 3 gt gt B L 073 21 gt gt A B ang il 1 1 z5 End of Example 4 2 6 Determinant Given a matrix A R then the Determinant is given det A A Given a 2x2 matrix A11 Az A Je Re Q21 422 Then det A A a11a22 421012 Tutorial LabVIEW MathScript Linear Algebra Examples 22 Linear Algebra Examples Example Determinant Find the determinant A 0 1 2 3 gt gt det A ENS 2 Notice that det AB det A det B and det 47 det A End of Example Example Determinant Determinants gt gt det A B ans 4 gt gt det A det B ans 4 gt gt Em UA ans 2 gt gt det A ans 2 End of Example 4 2 7 Inverse Matrices The inverse of a quadratic matrix A RY is defined by AT Tutorial LabVIEW MathScript 23 Linear Algebra Examples AA AAS For a 2x2 matrix we have d11 M 2x2 ER Q21 422 The inverse 47 is given by 1 a a 22 12 2x2 det A as 411 os Example Inverse Matr
5. H gskolen i Telemark Telemark University College Department of Electrical Engineering Information Technology and Cybernetics Tutorial LabVIEW MathScript HANS PETTER HALVORSEN 2011 02 11 LabVIEW MathScript File Edit View Operate Tools Window Help Output Window Variables Script History ans ERE SH C temp Lab IEW Datalsimple m function r simple a a r sin a gt gt inv A ans gt gt det A ans Command Window Ed of Technology Postboks 203 Kj lnes ring 56 N 3901 Porsgrunn Norway Tel 47 35 57 50 00 Fax 47 35 57 54 01 Preface This document explains the basic concepts of using LabVIEW MathScript For more information about LabVIEW visit my Blog http home hit no hansha What is LabVIEW LabVIEW short for Laboratory Virtual Instrumentation Engineering Workbench is a platform and development environment for a visual programming language from National Instruments The graphical language is named G What is MATLAB MATLAB is a tool for technical computing computation and visualization in an integrated environment MATLAB is an abbreviation for MATrix LABoratory so it is well suited for matrix manipulation and problem solving related to Linear Algebra MATLAB offers lots of additional Toolboxes for different areas such as Control Design Image Processing Digital Signal Pro
6. gt K 1 on a gain time constant and delay that you specify You can use gt tau 1 this function to create either a state space model or a transfer gt H sys_order1 K tau function model depending on the output parameters you specify Sys_order2 Constructs the components of a second order system model gt dr 0 5 based on a damping ratio and natural frequency you specify You gt wn 20 can use this function to create either a state space model or a gt num den sys_order2 wn dr 50 51 Error Reference source not found transfer function model depending on the output parameters you specify gt SysTF tf num den gt A B C D sys_order2 wn dr gt SysSS ss A B C D damp Returns the damping ratios and natural frequencies of the poles gt dr wn p damp SysIn of a system model pid Constructs a proportional integral derivative PID controller Ke 0 5 model in either parallel series or academic form Refer to the gt Ti 0 25 LabVIEW Control Design User Manual for information about gt SysOutTF pid Kc Ti these three forms eee conv Computes the convolution of two vectors or matrices acl 1 2 31 gt 02 3 41 gt C conv Cl C2 series Connects two system models in series to produce a model gt Hseries series H1 H2 SysSer with input and output connections you specify feedback Connects two system models toge
7. sis se se ee AA ER Ee AA AA AA ER AA AA AE Ge eke AA ee Ee Ee de ee ee ee 36 5 2 1 Bode Dir IR OR OE OR EE EE EO OR sede Kaori 36 LME EE EER GE EE Ree SEED eA eke ee ee be Le ee VD ee be el Gee ee Ee De ge Ee eis 40 6 MathScriptNod s is ss a A a ae ee Ee ie ee ek ee A a aa dass 42 Tutorial LabVIEW MathScript vi Table of Contents 6 1 Transferring MathScript Nodes between Computer iss se se ee RR RA AA Ee GR Ge RA 44 6 2 EEA EEE es EED o ah el e o Eg 44 6 3 EX ed ao inn tr KO es 48 TD MATLAB dei de EE OR ON N OR 49 Appendix A MathScript Functions for Control and Simulation esse se ee EE ER RA AA AR Ee RA 50 Tutorial LabVIEW MathScript LIntroduction to LabVIEW LabVIEW short for Laboratory Virtual Instrumentation Engineering Workbench is a platform and development environment for a visual programming language from National Instruments The graphical language is named G Originally released for the Apple Macintosh in 1986 LabVIEW is commonly used for data acquisition instrument control and industrial automation on a variety of platforms including Microsoft Windows various flavors of UNIX Linux and Mac OS X The latest version of LabVIEW is version LabVIEW 2009 released in August 2009 Visit National Instruments at www ni com The code files have the extension vi which is an abbreviation for Virtual Instrument LabVIEW offers lots of additional Add Ons and Toolkits 1 1 Dataflow programmi
8. SysCom PET 2 2 SysCon set SysCon inputdelay 6 outputdelay 1 1 SysDel pade SysCon 2 delay 1 2 order 3 num den pade delay order End of Example Tutorial LabVIEW MathScript 36 Control Design and Simulation 5 2 Frequency Response Analysis The frequency response of a system is a frequency dependent function which expresses how a sinusoidal signal of a given frequency on the system input is transferred through the system Each frequency component is a sinusoidal signal having a certain amplitude and a certain frequency The frequency response is an important tool for analysis and design of signal filters and for analysis and design of control systems The frequency response can found experimentally or from a transfer function model The frequency response of a system is defined as the steady state response of the system to a sinusoidal input signal When the system is in steady state it differs from the input signal only in amplitude A and phase angle w If we have the input signal u t U sinwt The steady state output signal will be y t UA sin wt p Aand d isa function of the frequency w so we may write A A w o w For a transfer function H S We have A w HG p w Ho Where H jw is the frequency response of the system i e we may find the frequency response by setting s jw inthe transfer function 5 2 1 Bode Diagram Bode diagrams are useful
9. frequency response crosses 180 degrees crossover frequency W4g9 ZH jwigo Examples The following example illustrates the use of the margin function num 1 den fi 5 6 H tf num den margin H End of Example Example Given the following system 1 TEO We want to plot the Bode diagram and find the crossover frequencies for the system using MathScript We use the following functions tf bode margins and margin e gmfisthe gain margin frequencies in radians second A gain margin frequency indicates where the model phase crosses 180 degrees e gm Returns the gain margins of the system Tutorial LabVIEW MathScript 39 Control Design and Simulation e pmf Returns the phase margin frequencies in radians second A phase margin frequency indicates where the model magnitude crosses O decibels e pm Returns the phase margins of the system e We get LabVIEW MathScript File Edit Yiew Operate Tools Window Help Output Window phase_data 0 99931 0 68233 eres EE Variables Script History Command Window SHa PB M iWorkiLablLab Work MathScript Lab Solutions Code Task Al Transfer Function A num 1 den1 1 0 den2 1 1 den3 1 1 den conv den1 conv den2 den3 H tf num den Bode Plot bode H Margins and Phases wlist 0 01 0 1 0 2 0 5 1 10 100 mag phase w bode H wlist magdB 20 log10 mag convert
10. return the step response of the model outputs If the model is in state space form you also can use this function to return the step response of the model states This function assumes the initial model states are zero If you do not specify an output this function creates a plot Example Given the following system s 1 H s s s s 3 We will plot the time response for the transfer function using the step function The result is as follows File Edit View Project Operate Tools Window Help Graph Step Response HE v D 2 Te T 2 Time s The MathScript code EN N sed Wi Wp ol Sy step H End of Example Tutorial LabVIEW MathScript 6MathScript Node The MathScript Node offers an intuitive means of combining graphical and textual code within LabVIEW The figure below shows the MathScript Node on the block diagram represented by the blue rectangle Using MathScript Nodes you can enter m file script text directly or import it from a text file fpts 0 fstoplow fpasslow stop 2 amplitude 90 1 0 1 0 tomskow MZ bes fir2 taps fpts amplitude H F freqz b 1 512 1 BEN passion Ts log abs H MathScript Node You can define named inputs and outputs on the MathScript Node border to specify the data to transfer between the graphical LabVIEW environment and the textual MathScript code You can associate m file script vari
11. script commands and see immediate results variables and commands history The window includes a 4 5 LabVIEW MathScript command line interface where you can enter commands one by one for quick calculations script debugging or learning Alternatively you can enter and execute groups of commands through a script editor window As you work a variable display updates to show the graphical textual results and a history window tracks your commands The history view facilitates algorithm development by allowing you to use the clipboard to reuse your previously executed commands You can use the LabVIEW MathScript Window to enter commands one at time You also can enter batch scripts in a simple text editor window loaded from a text file or imported from a separate text editor The LabVIEW MathScript Window provides immediate feedback in a variety of forms such as graphs and text 3 Labrie Man vlg Jou Mn CR Yew Queda Ince dos He Ospa a tee II rd Pet help entet help classes AE He Cresse Textual Output Variables Script MathScript Command Window es Command Window ier 1 Colour Example Tutorial LabVIEW MathScript 6 LabVIEW MathScript LabVIEW MathScript File Edit View Operate Tools Window Help Output Window Variables Script History ans Gus Pb C temp LabVIEW Datalsimple m Function r simple a La 0 95892 r si
12. to dB mag phase w bode H mag data w magdB phase data w phase Crossover Frequency amf gm pmf pm margins H margin H Line 6 Column 1 Below we see the Bode diagram with the crossover frequency and the gain margin and phase margin for the system plotted in Tutorial LabVIEW MathScript 40 Control Design and Simulation Plot 2 File Items Tools Help Graph 1 50 o i Gain Margin PM Crossover r o 1 Magnitude dB 1 10 Frequency rad s Graph 2 yO 10 180 k deg Phase Margin GM Crossover Phase deg I 10 Frequency rad s End of Example Time Response Class timeresp Description Use members of the timeresp class to create generic linear simulations and time domain plots for step inputs impulse inputs and initial condition responses Below we see the different functions available in the timeresp class Function Description impulse Creates the impulse response plot of a system model Creates the initial response plot of a system model Creates the linear simulation plot of a system model randvector Generates one or two random vectors ste Creates the step response plot of a system model Function step Description Tutorial LabVIEW MathScript 41 Control Design and Simulation This function creates a step response plot of the system model You also can use this function to
13. LL Build the path to the header file If this example is built into an lapplication it will look for the file lin the application s data directory theta 2 pP N x Cx r cos theta y Cy r sin theta lib call n SetCursorPos x y sone Path to Windows DLL if wlib_isloaded n lib_unload n lib_load library header alias n end ircle Centre pixels from the screen origin ET End of Example Example Using m files in the MathScript Node Use the LabVIEW MathScript to create a m file script or you may use MATLAB to create the same script Tutorial LabVIEW MathScript 46 MathScript Node LabVIEW MathScript File Edit View Operate Tools Window He EIE Output Window For help enter help classes gt gt Unknown symbol on line 1 A gt gt A 1 2 3 4 b 5 6 x inv A b Unknown symbol on line 1 A _ Variables Script History Command Window Swe c Temp LabV IEW Datatcalox m A 1 2 34 b 5 6 x inv A b A Line 4 Column 1 Right click on the border of the MathScript Node and select Import and then select the m file you want to import into the Node A 1 2 3 4 b 5 6 x inv A b visible Items Help Examples Description nd Tip
14. MathScript 31 Control Design and Simulation The differential equations x4 2x4 6u X2 2X4 May be written on state space form EIE ole ole Function ss Description This function constructs a continuous or discrete linear system model in state space form You also can use this function to convert transfer function and zero pole gain models to state space form Examples Creates a state space model eye 2 OS B vEOUESS SE VA By C OO BP de oe Converts a zero pole gain model to state space form 1 dl I il SwiSllia zoe PIE SysOutss ss SyslIn a oO N End of Example 513 Transfer function The transfer function of a linear system is defined as the ratio of the Laplace transform of the output variable to the Laplace transform of the input variable y s H S Function tf Description This function creates a continuous or discrete linear system model in transfer function form You also can use this function to convert zero pole gain and state space models to transfer function form Tutorial LabVIEW MathScript 32 Control Design and Simulation Examples SI SA This specifies that you want to create the continuous transfer function s 1 After you enter this command you can use LabVIEW MathScript operands on this transfer function to define a zero pole gain or transfer function model Sis Olle Zip Kanes 2 e 1 This exa
15. ables with LabVIEW graphical programming by wiring Node inputs and outputs Then you can transfer data between m file scripts with your graphical LabVIEW programming The textual m file scripts can now access features from traditional LabVIEW graphical programming The MathScript Node is available from LabVIEW from the Functions Palette Mathematics gt Scripts amp Formulas 42 43 MathScript Node Scripts amp Formulas Siew 7 ol Formula Node Script Nodes FEE fn Formula Formula Parsing 2 ft 1D amp 2D Eval Calculus If you click Ctrl H you get help about the MathScript Node Context Help MathScript Node input variable A 1 Sum eye size A optional 2 ri 1 n input variable M 3 Sum Sum AN ifFactorial Delta output variable optional 4 end optional Delta SumA exprox 4 error in error out Executes LabVIEW MathScripts and your other text based scripts using the MathScript RT Module engine You can use the MathScript Node to evaluate scripts that you create in the LabYIEW MathScript Window If a MathScript Node contains a warning glyph LabYIEW operates with slower run time performance For the node You can modify your script to remove the warning glyph from the MathScript Node and improve run time performance Detailed help Click Detailed help in order to get more information about the MathScript Node Use the NI Example Find
16. alc_average x y A This Function calculates the average of 2 numbers av x y 2 Scripts A script is a sequence of MathScript commands that you want to perform to accomplish a task When you have created the script you may save it as a m file for later use LabVIEW MathScript File Edit View Operate Tools Window Help Output Window A gt 3 gt gt mean x File Items Tools Help Variables Script History Salsa M Work Tutorials LabVIEW Lab IEW MathScript Code Examples MathScript t 0 0 1 10 y cos t plot t y Run the Script Type Commands in your script here a Line 4 Column 1 You may also have multiple Script Windows open at the same time by selecting New Script Editor in the File menu Tutorial LabVIEW MathScript 12 LabVIEW MathScript LabVIEW MathScript File LabVIEW MathScript Properties Ctrl I Recent Projects Recent Files Exit This gives SEE i DEK Tutorial LabVIEW MathScript 13 LabVIEW MathScript 3 5 Flow Control This chapter explains the basic concepts of flow control in MathScript The topics are as follows e If else statement e Switch and case statement e Forloop e While loop ll If else Statement The if statement evaluates a logical expression and executes a group of statements when the expression i
17. cessing etc What is MathScript MathScript is a high level text based programming language MathScript includes more than 800 built in functions and the syntax is similar to MATLAB You may also create custom made m file like you do in MATLAB MathScript is an add on module to LabVIEW but you don t need to know LabVIEW programming in order to use MathScript If you want to integrate MathScript functions built in or custom made m files as part of a LabVIEW application and combine graphical and textual programming you can work with the MathScript Node In addition to the MathScript built in functions different add on modules and toolkits installs additional functions The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit install lots of additional functions You can more information about MathScript here http www ni com labview mathscript htm How do you start using MathScript You need to install LabVIEW and the LabVIEW MathScript RT Module When necessary software is installed start MathScript by open LabVIEW Getting Started Latest from ni com News HE Empty Project Technical Content 3 Real Time Project More Example Programs Training Resources Online Support Open Discussion Forums R M 4ir Heater HIL Simulation lvproj ed M1 WocabularyWocabulary Ivproj Code Sharing KnowledgeBase ml M 1 CodelSlope and Intercept vi f M Sub I CodelLinear Scaling
18. e components of a second order system model based on a damping ratio and natural frequency you specify You can use this function to create either a state space model or a transfer function model depending on the output parameters you specify Example Examples of how to use the sys_order2 function cle 0 5 wn 20 num den sys order2 wn dr SysTF tf num den lA Ey Cy DI sys oxelei2 way ele SS SS SAS D End of Example Class connect Tutorial LabVIEW MathScript 34 Control Design and Simulation Description Use members of the connect class to connect systems models together in various configurations Below we see the different functions available in the connect class Function Description wconcat Vertically concatenates two or more system models Function series Description This function connects two system models in series to produce a model SysSer with input and output connections you specify The input models must be either continuous models or discrete models with identical sampling times Example Here is an example of how to use the series function SysIn 1 sade ti EI i 31 Sysim 2 zoki ll LI 1 SS SES SES mm il Syelia 2 End of Example Class convert Description Use members of the convert class to convert a continuous system model to a discrete model convert a discrete model to a continuous model and resample a discr
19. er in order to find examples Tutorial LabVIEW MathScript 44 MathScript Node NI Example Finder Browse Search Submit Double click an example to open it Information input 4 Browse according to E instr O Task internet C lvdsc Directory Structure 3 lvoop EE LabVIEW Zone c a CONNECT TO YOUR COMMUNITY MatiSerpt Heat Equation Heat Equation vi E MathScript Parallel Fractal Parallel Fractal split vi Parallel Fractal typical vi Update Fractal vi E MathScript Shared Libraries MathScript Calling a Windows DLL vi MathScript Using shared libraries vi MathScript Shared Libraries lyproj E MathScript using Riemann Zeta MathScript using Riemann Zeta vi MathScript Fractal vi Include ni com examples MathScript Fundamentals vi ad ni com query timeout C Max C measure Hardware i EJ Modulation Find hardware motion Requirements Visit LabVIEW Zone uuu Fue Limit results to hardware Add to Favorites Setup Help Close 6 1 Transferring MathScript Nodes between Computers If a script in a MathScript Node calls a user defined function LabVIEW uses the default search path list to link the function call to the specified m file After you configure the default search path list and save the VI that contains the MathScript Node you do not need to reconfigure the MathScript search path list when you open the VI on a different comp
20. ete model You also can use members of this class to incorporate delays into a system model Below we see the different functions available in the convert class Tutorial LabVIEW MathScript 35 Control Design and Simulation Function Description cto d Converts a continuous system model to a discrete model d to c Converts a discrete system model to a continuous one d to d Resamples a discrete system model delay to z Incorporates delays into a discrete system model distributedelay Minimizes transport delay in a system model pade Incorporates delays into a continuous system model by using Pade approximation polycoef Specifies whether transfer function coefficients are in ascending or descending direction ss to ss Applies a state transformation to a system model 5 1 6 Pad approximation The Transfer function of a time delay is H s e Ts TS In some situations it is necessary to substitute e with an approximation e g the Pad approximation 1 kis ks kps 1ks kos kps TS e Function pade Description This function incorporates time delays into a system model using the Pade approximation method which converts all residuals You must specify the delay using the set function You also can use this function to calculate coefficients of numerator and denominator polynomial functions with a specified delay Example Examples of how to use the pade function
21. ices Inverse matrix A 0 i 2 3 gt gt inv A ans i 5000 0 5000 1 0000 0 End of Example Notice that AA tS AC ASI gt Prove this in MathScript 4 3 Eigenvalues Given A RAT then the Eigenvalues is defined as det Al A 0 Example Eigenvalues Find the Eigenvalues A 0 iL 2 3 gt gt eig A ans 1 2 Tutorial LabVIEW MathScript 24 Linear Algebra Examples End of Example 4 4 Solving Linear Equations Given the linear equation Ax b with the solution x Ath Assuming that the inverse of A exists Example Solving Linear Equations Solving the following equation The equations X 2x 5 3x 4x2 6 may be written Ax b 6 IEA where TE sl ve The solution is A 1 2 3 4 gt gt l 5761 b 5 6 gt gt x inv A b Tutorial LabVIEW MathScript 25 Linear Algebra Examples x 4 0000 4 5000 In MathScript you could also write x A1b which should give the same answer This syntax can also be used when the inverse of A don t exists End of Example Example Solving Linear Equations Illegal operation gt gt ASIL 223 ey El gt gt x inv A b SN Matrix must be square gt gt x A b g sA 500Y 4 1786 End of Example 4 5 LU factorization LU factorization of A R is given by A LU where L is a lower triangular matrix U is a upper triangular mat
22. ies each VI can be easily tested before being embedded as a subroutine into a larger program The graphical approach also allows non programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar The LabVIEW 2 Introduction to LabVIEW programming environment with the included examples and the documentation makes it simple to create small applications This is a benefit on one side but there is also a certain danger of underestimating the expertise needed for good quality G programming For complex algorithms or large scale code it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management The most advanced LabVIEW development systems offer the possibility of building stand alone applications Furthermore it is possible to create distributed applications which communicate by a client server scheme and are therefore easier to implement due to the inherently parallel nature of G code 1 3 Benefits One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion These present themselves as graphical nodes The abstraction layers offer standard software interfaces to communicate with hardware devices The pr
23. in frequency response analysis The Bode diagram consists of 2 diagrams the Bode magnitude diagram A w and the Bode phase diagram Tutorial LabVIEW MathScript 37 Control Design and Simulation The A w axis is in decibel dB Where the decibel value of x is calculated as x dB 20log 9x The w axis is in degrees not radians Function bode Description This function creates the Bode magnitude and Bode phase plots of a system model You also can use this function to return the magnitude and phase values of a model at frequencies you specify If you do not specify an output this function creates a plot Examples We have the following transfer function y _ 1 AO A We want to plot the Bode diagram for this transfer function File Items Tools Help Bode Plots Magnitude 0 1 o 20 30 Do D o A oO EE a 1 1 Frequency rad s In MathScript we could write num 1 den 1 1 H1 tf num den bode H1 End of Example Tutorial LabVIEW MathScript 38 Control Design and Simulation Function margin Description This function calculates and or plots the smallest gain and phase margins of a single input single output SISO system model The gain margin indicates where the frequency response crosses at O decibels crossover frequency we lH Gwe w is also the bandwidth of the system The phase margin indicates where the
24. ity matrix of size n can be generated using the function eye and matrices of any size with zeros or ones can be generated with the functions zeros and ones respectively gt gt eye 3 ans OO i 1 SS weiros 2 3 ans OOO 00 0 OMS ano ans EE 1 a Tutorial LabVIEW MathScript LabVIEW MathScript 3 4 Useful commands Here are some useful commands Command Description eye x eye x y Identity matrix of order x ones x ones x y A matrix with only ones zeros x zeros x y A matrix with only zeros diag x y z Diagonal matrix size A Dimension of matrix A ar Inverse of matrix A Calling functions In MathScript MathScript includes more than 800 built in functions that you can use e g in a previous task you used the plot function Example Built in Functions Given the vector gt x 1 2 5 6 8 9 3 gt Find the mean value of the vector x gt Find the minimum value of the vector x gt Find the maximum value of the vector x The MathScript Code is sell 2 6 8 SN mean x min x max x End of Example Tutorial LabVIEW MathScript 10 LabVIEW MathScript User Defined Functions In MathScript MathScript includes more than 800 built in functions that you can use but sometimes you need to create your own functions To define your own function in MathScript use the following
25. l Derivative PID algorithm is the most common control algorithm used in industry In PID control you must specify a process variable and a setpoint The process variable is the system parameter you want to control such as temperature pressure or flow rate and the setpoint is the desired value for the parameter you are controlling A PID controller determines a controller output value such as the heater power or valve position The controller applies the controller output value to the system which in turn drives the process variable toward the setpoint value Then the PID controller calculates the controller action u t E fe de u t EK el edt Tar Where Tutorial LabVIEW MathScript 30 Control Design and Simulation Ke Controller gain T Integral time Ta Derivative time And e is the error e SP PV SP Setpoint PV Process Variable Function pid Description Constructs a proportional integral derivative PID controller model in either parallel series or academic form Examples 0 5 0 25 SysOutTF pid Kc Ti academic End of Example 5 1 2 State space model A state space model is just a structured form or representation of the differential equations for a system A linear State space model x Ax Bu y Cx Du where x is the state vector and u is the input vector A is called the system matrix and is square in all cases Example Tutorial LabVIEW
26. le supports most of the functionality available in MATLAB the syntax is also similar For more details see http zone ni com devzone cda tut p id 3257 3LabVIEW MathScript 3 1 Introduction Requires MathScript RT Module How do you start using MathScript You need to install LabVIEW and the LabVIEW MathScript RT Module When necessary software is installed start MathScript by open LabVIEW Getting Started File Operate Tools Help Latest from ni com News sy Empty Project Technical Content a Real Time Project More Example Programs Training Resources Online Support Open Discussion Forums R M 4ir Heater HIL Simulation lvproj EE M 1 WocabularyWocabulary Ivproj Code sharing KnowledgeBase ls M Code Slope and Intercept vi Request Support f M Sub I Code Linear Scaling vi Help ml C tmpitest2 vi f M Slope and Intercept vi Getting Started with LabVIEW LabVIEW Help Browse List of All New Features Targets Examples Mobile Project Q Find Examples In the Getting Started window select Tools gt MathScript Window d di File Operate Help ad Measurement amp Automation Explorer Fe nn reld Instrumentation a Real Time Mad RI MathScript Window DSC Module New IMAQ Vision gt Latest from ni com The LabVIEW MathScript Window is an interactive interface in which you can enter m file
27. mple constructs a zero pole gain model with a gain of 4 a zero at 2 and a pole at 1 SysOucws 37 SA r 2D A SS SN 8 This example constructs the transfer function model 3513 2 4514 8 End of Example 5 1 4 First Order Systems The following transfer function defines a first order system HEEN es Where K is the gain T is the Time constant Function sys_order1 Description This function constructs the components of a first order system model based on a gain time constant and delay that you specify You can use this function to create either a state space model or a transfer function model depending on the output parameters you specify Inputs K Specifies the gain matrix K is a real matrix tau Specifies the time constant in seconds which is the time required for the model output to reach 63 of its final value The default value is O Tutorial LabVIEW MathScript 33 Control Design and Simulation delay Specifies the response delay of the model in seconds The default value is O Examples ix 0 52 cau 1 39 SyseQuiella sys Orceri K tau End of Example 5 1 5 Second Order Systems A standard second order transfer function model may be written like this y s Kwo K MOS Fruor ME Where K is the gain zetais the relative damping factor W rad s is the undamped resonance frequency Function sys_order2 Description This function constructs th
28. n a gt gt inv A ans gt gt det A ans 2 EE EE Command Window ed Line 3 Column 11 End of Example 3 2 Help You may also type help in your command window gt gt help Or more specific e g gt gt help plot 3 3 Examples advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program and its syntax All examples in the text are outlined in a frame like this gt gt Tutorial LabVIEW MathScript 7 LabVIEW MathScript This is commands you should write in the Command Window You type all your commands in the Command Window will use the symbol gt gt to illustrate that the commands should be written in the Command Window Example Matrices Defining the following matrix gt II b 3 The syntax is as follows gt gt A r20 3 Or gt gt A 1 2704 31 If you for an example want to find the answer to a b wherea 4 b 3 gt gt a 4 gt gt b 3 gt gt a b MathScript then responds ans 7 MathScript provides a simple way to define simple arrays using the syntax init increment terminator For instance gt gt array Is2 array 135 7 The code defines a variable named array or assigns a new value to an existing variable with the name array which is an array consisting of the value
29. ng The programming language used in LabVIEW also referred to as G is a dataflow programming language Execution is determined by the structure of a graphical block diagram the LV source code on which the programmer connects different function nodes by drawing wires These wires propagate variables and any node can execute as soon as all its input data become available Since this might be the case for multiple nodes simultaneously G is inherently capable of parallel execution Multi processing and multi threading hardware is automatically exploited by the built in scheduler which multiplexes multiple OS threads over the nodes ready for execution 1 2 Graphical programming LabVIEW ties the creation of user interfaces called front panels into the development cycle LabVIEW programs subroutines are called virtual instruments VIs Each VI has three components a block diagram a front panel and a connector panel The last is used to represent the VI in the block diagrams of other calling Vis Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument However the front panel can also serve as a programmatic interface Thus a virtual instrument can either be run as a program with the front panel serving as a user interface or when dropped as a node onto the block diagram the front panel defines the inputs and outputs for the given node through the connector pane This impl
30. ovided driver interfaces save program development time The sales pitch of National Instruments is therefore that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems A new hardware driver topology DAQmxBase which consists mainly of G coded components with only a few register calls through NI Measurement Hardware DDK Driver Development Kit functions provides platform independent hardware access to numerous data acquisition and instrumentation devices The DAQmxBase driver is available for LabVIEW on Windows Mac OS X and Linux platforms For more information about LabVIEW visit my Blog http home hit no hansha 1 4 LabVIEW MathScript RT Module The LabVIEW MathScript RT Module is an add on module to LabVIEW With LabVIEW MathScript RT Module you can e Deploy your custom m files to NI real time hardware e Reuse many of your scripts created with The MathWorks Inc MATLAB software and others e Develop your m files with an interactive command line interface e Embed your scripts into your LabVIEW applications using the MathScript Node Tutorial LabVIEW MathScript 2LabVIEW MathScript RT Module You can work with LabVIEW MathScript through either of two interfaces the LabVIEW MathScript Interactive Window or the MathScript Node You can work with LabVIEW MathScript RT Module through both interactive and
31. programmatic interfaces For an interactive interface in which you can load save design and execute your m file scripts you can work with the MathScript Interactive Window To deploy your m file scripts as part of a LabVIEW application and combine graphical and textual programming you can work with the MathScript Node The LabVIEW MathScript RT Module complements traditional LabVIEW graphical programming for such tasks as algorithm development signal processing and analysis The LabVIEW MathScript RT Module speeds up these and other tasks by giving users a single environment in which they can choose the most effective syntax whether textual graphical or a combination of the two In addition you can exploit the best of LabVIEW and thousands of publicly available m file scripts from the web textbooks or your own existing m script applications LabVIEW MathScript RT Module is able to process your files created using the current MathScript syntax and for backwards compatibility files created using legacy MathScript syntaxes LabVIEW MathScript RT Module can also process certain of your files utilizing other text based syntaxes such as files you created using MATLAB software Because the MathScript RT engine is used to process scripts contained ina MathScript Windows or MathScript Node and because the MathScript RT engine does not support all syntaxes not all existing text based scripts are supported LabVIEW MathScript RT Modu
32. rix The MathScript syntax is L U lu A Example LU Factorization Find L and U gt gt A 1 2 3 4 gt gt L U lu A T 0 3333 1 0000 1 0000 0 3 0000 4 0000 Tutorial LabVIEW MathScript 26 Linear Algebra Examples 0 0 6667 End of Example Or sometimes LU factorization of A R is given by A LU LDU where Dis a diagonal matrix The MathScript syntax is L U P lu A Example LU Factorization Find L U and P gt gt A 1 2 3 4 A 1 2 3 4 gt gt L U P 1u A TE iL OOOO 0 0 8333 1 0000 UW SEO OOO 4 0000 0 0 6667 P 0 1 ile 0 End of Example 4 6 The Singular Value Decomposition SVD The Singular value Decomposition SVD of the matrix A RAT is given by As USVT where U is a orthogonal matrix Vis a orthogonal matrix Tutorial LabVIEW MathScript 27 Linear Algebra Examples S is a diagonal singular matrix Example SVD Decomposition Find S Vand D gt gt B 223 4l gt gt U S V svd A U 0 4046 0 9145 LS 0 4046 S 5 4650 0 0 0 5660 MES 0 S760 0 8174 0 8174 0 5760 End of Example 4 7 Commands Command Description L U 1u A L U P 1u A LU Factorization U S V svd A Singular Value Decomposition SVD Tutorial LabVIEW MathScript 5Control Design and Simulation Using LabVIEW MathScript for Control Design purposes yo
33. s 1 3 5 7 and 9 That is the array starts at 1 the init value increments with each step from the previous value by 2 the increment value and stops once it reaches or to avoid exceeding 9 the terminator value The increment value can actually be left out of this syntax along with one of the colons to use a default value of 1 Se ad ies ari Tutorial LabVIEW MathScript 8 LabVIEW MathScript L234 5 The code assigns to the variable named ari an array with the values 1 2 3 4 and 5 since the default value of 1 is used as the incrementer Note that the indexing is one based which is the usual convention for matrices in mathematics This is atypical for programming languages whose arrays more often start with zero Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to terminate each row The list of elements should be surrounded by square brackets Parentheses are used to access elements and subarrays they are also used to denote a function argument list S gt A lo 3 2 18 5 10 lil Se 9 6 7 127 A 15 14 1 JA le s 2 is OS S F 12 a 15 14 T SS A Z 3 ans 11 Sets of indices can be specified by expressions such as 2 4 which evaluates to 2 3 4 For example a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as SS IAZ Ra 384 ans ii B 7 12 14 1 A square ident
34. s true The optional elseif and else keywords provide for the execution of alternate groups of statements An end keyword which matches the if terminates the last group of statements The groups of statements are delineated by the four keywords no braces or brackets are involved Example If Else Statement Test the following code n 5 ir gt A M eye n elseif n lt 2 M zeros n else M ones n end End of Example 35 2 Switch and Case Statement The switch statement executes groups of statements based on the value of a variable or expression The keywords case and otherwise delineate the groups Only the first matching case is executed There must always be an end to match the switch Example Switch and Case Statement Test the following code n 2 switch n Tutorial LabVIEW MathScript 14 LabVIEW MathScript Case 1 M eye n case 2 M zeros n case 3 M ones n end End of Example 3 5 3 For loop The for loop repeats a group of statements a fixed predetermined number of times A matching end delineates the statements Example For Loop Test the following code for n 1 m r n rank magic n End of Example 3 5 4 While loop The while loop repeats a group of statements an indefinite number of times under control of a logical condition A matching end delineates the statements Example While Loop Test the following code MED
35. st gain and phase margins ofa gt 2um 1 single input single output SISO system model The gain margin den 1 5 6 indicates where the frequency response crosses at 0 decibels The phase margin indicates where the frequency response crosses 180 degrees Use the margins function to return all gain and phase margins of a SISO model Tutorial LabVIEW MathScript gt H tf num den margin H 52 Error Reference source not found margins Calculates all gain and phase margins of a single input single output SISO system model The gain margins indicate where the frequency response crosses at O decibels The phase margins indicate where the frequency response crosses 180 degrees Use the margin function to return only the smallest gain and phase margins of a SISO model gt gmf gm pmf pm margins H For more details about these functions type help cdt to get an overview of all the functions used for Control Design and Simulation For detailed help about one specific function type help lt function_name gt Plots functions Here are some useful functions for creating plots plot figure subplot grid axis title xlabel ylabel semilogx for more information about the plots function type help plots Tutorial LabVIEW MathScript TW Op Bae H gskolen i Telemark Telemark University College Faculty of Technology Kj lnes Ring 56 N 3914 Porsgr
36. syntax Boe IS CULES meme EE MEE o documentation Here is the procedure for creating a a user defined function in MathScript LabVIEW MathScript N Edit View Operate Tools Window Help New VI Ctrl New Save your function as a m file History Open CHO Close Ctrl C tmp MathScript add m_ function total add x y Close Al this Function add 2 numbers total x y Save Ctrl S Save As Add Search Folder New Script Editor for your Code New Project Open Project Recent Projects Recent Files C Ate reanhsengt Exit Add your folder where your code is located here Working deectory Crop Ser The fust rectory in the Search paths for m Fles ist species the Working rectory NOTE Changes you make to the search path kst apply ony to the LabVIEW MathScript Window Command Window lada 3 5 Aly and Save o cancel mp Test your function in the Command window a 0 Create your function in the Script window Line 1 Column 18 9 0f3 Tutorial LabVIEW MathScript 11 LabVIEW MathScript LabVlEW MathScript File Edit View Operate Tools Window Help Output Window Variables 3 4 gt gt z calc_average x y Script History SH M Work Lab Lab Work MathScript Lab Solutions Codel Command Window z calc_average x y function av c
37. ther to produce a closed loop SysClosed feedback SysIn_1 model using negative or positive feedback connections oi a ss Constructs a model in state space form You also can use this vA eyet2 function to convert transfer function models to state space gt B 0 1 form gt C B gt SysOutSS ss A B C ssinfo Returns information about a state space system model gt A l 17 1 2 gt B 1 2 56 12 gt D 0 gt SysInSS ss A B C D gt A B C D Ts ssinfo SysInSS pade Incorporates time delays into a system model using the Pade gt num den pade delay order approximation method which converts all residuals You must gt A B C D pade delay order specify the delay using the set function You also can use this function to calculate coefficients of numerator and denominator polynomial functions with a specified delay bode Creates the Bode magnitude and Bode phase plots of a system gt num 4 model You also can use this function to return the magnitude gt den 2 1 and phase values of a model at frequencies you specify If you gt H t num den do not specify an output this function creates a plot gt bode H bodemag Creates the Bode magnitude plot of a system model If you do gt mag wout bodemag SysIn not specify an output this function creates a plot gt mag wout bodemag SysIn wmin wmax gt mag wout bodemag SysIn wlist margin Calculates and or plots the smalle
38. u need to install the Control Design and Simulation Module in addition to the MathScript RT Module itself Use the Control Design MathScript RT Module functions to design analyze and simulate linear controller models using a text based language The following is a list of Control Design MathScript RT Module classes of functions and commands that LabVIEW MathScript supports Getting help about MathScript functions regarding the Control Design Toolkit CDT type help cdt in the Command Window in the MathScript environment The following function classes exist reduce ssanals State space analysis functions We will go through some of the classes and function in detail below 5 1 State space models and Transfer functions 28 29 Control Design and Simulation MathScript offers lots of functions for defining and manipulate state space models and transfer functions Class contruct Description Use functions in the construct class to construct linear time invariant system models and to convert between model forms Below we see the different functions available in the construct class Function Description zid Below we will give some examples of how to use the most import functions in this class ss Creates a system model in or converts a model to state space form sys filter Constructs a digital filter in transfer function form g Sek PID Currently the Proportional Integra
39. unera inn ee ee ee ee ee 10 el se N EE RE EE ER OO RO RE EE 11 3 5 Flow CONT ON RE EE EE ER EE N 13 3 5 1 IESER RE EEt 13 3 5 2 Switch and Case Statement iid RE EER REDS Es ii dad 13 3 5 3 dele MERE AE N EA OE EE 14 3 5 4 WIE ele MEER EE EA OR N EE OE EE EE ON OE TE 14 3 6 ride RE EE EE A EE N EE 15 4 Linear Algebra Example Sie sees EES diiniita 17 v Table of Contents 4 1 Med 17 4 2 Matrices ti N a A id ed 18 4 2 1 TNA ia 18 4 2 2 DOM EEEE E A a a RE N 19 4 2 3 TO ii A Hane EE EE 20 4 2 4 MatricMultiplicitiON it as Es GE EE a GED Ee Ee Ge GE di ge ee Ge 20 4 2 5 Matrix Addition AE RE OE ER IR ER Alaa 21 4 2 6 DETENER HN EE 21 4 2 7 Inverse Matrices unit ia ia 22 4 3 EA MUS A A th AA AA A A Caen aS 23 4 4 Solving Linear EduatioNSisis SS iia 24 4 5 BU le deer ele N ME RE NE RE OR EE 25 4 6 The Singular Value Decomposition SVD iese es se ee RA ER AA EE RA ee AA ee ee ee Ge 26 4 7 COMME 27 5 Control Design and Simulation ee se ee ee ER ER RA AA ER Ee RA AA ER Ee RA ee AE Ge ee AA ee 28 5 1 State space models and Transfer fUNCtiONS ooccccccnononoonnnnnnnnonanononnnnncnnnananononnnnncnnnnnnnnnanons 28 5 1 1 PDA 29 5 1 2 Statesspaceimodel ia da A e A Ee ee ee DE dad id 30 5 1 3 Transfer oe del EE ME EE N EE eee 31 5 1 4 ESCORTS RA ER RR EE OR EE N 32 5 1 5 Second Order Systems Es RD SEE Ee di ves ater DE EE VER ibas 33 5 1 6 SA EE aust Se Ee ee Ge Ee gen Ge ee ge Se ee EE 35 5 2 Frequency Response Analysis
40. unn Norway www hit no Hans Petter Halvorsen M Sc Telemark University College Department of Electrical Engineering Information Technology and Cybernetics Phone 47 3557 5158 E mail hans p halvorsen hit no Blog http home hit no hansha Room B 237a
41. uter because LabVIEW looks for the m file in the directory where the m file was located when you last saved the VI However you must maintain the same relative path between the VI and the m file 6 2 Examples Example Using the MathScript Node Here is an example of how you use the MathScript Node On the left border you connect input variables to the script on the right border you have output variables Right click on the border and select Add Input or Add Output Tutorial LabVIEW MathScript 45 MathScript Node The MathScript Node can be Found in the Functions gt gt Mathematics gt gt Scripts amp Formulas Palette L 2 Comments are preceded by x 123 Square each element of x to get y y x 02 Extract y 1 yl y 1 10 Calculate the Dot Product of x an d dot x y OD OD N PUB LI N e 1 To add an input output 2 Scripts can be typed in 3 To change the datatype 4 Use the Index Array VI to to the MathScript node the MathScript node or of an output right click on extract the first element right click on the node and imported by right clicking on the output and select of y Outside of the select Add Input Add the node and selecting Choose Data Type MathScript node LabVIEW Output Import arrays are zero indexed End of Example Example Calling a Windows DLL Calculate the cursor position and call the Windows DLL Unload the Windows D
42. vi ml C tmpitest2 vi e M Slope and Intercept vi Browse Request Support Help Getting Started with LabVIEW LabVIEW Help List of All New Features Targets Examples Mobile Project AL Find Examples In the Getting Started window select Tools gt MathScript Window Getting Started File Operate M5 Measurement amp Automation Explorer Instrumentation New IMAQ Vision gt Latest from ni com Table of Contents AT RE EE vadeutcesotiucdvaebsgstesabessedvaadedaecbiac dacaesadentanccecsibestansage ii TAD Content ido IE iv 1 Introduction to LabVIEW sce seein EE ER Bn ane id 1 1 1 Dataflow Programming cccccccccsssccceesssceceessecececsseeececsssseceesseseceesssecsesssecseseseeceesesaeesesesaeees 1 1 2 Graphical edele li AR N OE RE OE N EE ER N EN 1 1 3 EE RT EE N ER OE OE EE RE 2 1 4 LabVIEW MathScript RT Module sees esse se Ee AE AA GR ee AA EE Ge RA AA ee Ee Re de ee ee 2 2 LabVIEW MathScript RT Module iese sesse se se ee ee AR Ee Re AA AA ER Ee AA ee AA Ee ede AR Ee ede ee ee ee 3 3 Elouise ge EE N RR ME RR EE OE OE OE N ON 4 3 1 INtOdUciON EE RE EI 4 3 2 A E E OE RE DE 6 33 Elle MR EE AR RE RE OE ER EN 6 3 4 Useful COMMANGS RE OR EE EE oneal 9 Calling functions In MathScript eise sesse ee RA Ge AA ee GR Re Ge AA Ee AR corran AA Ge de ee ee Ge rn ee de ee ee ee 9 User Defined Functions In MathScript iese se ees se ee ee Re ER Ee ee ee
43. while m gt 1 il im ig zeros m end End of Example Tutorial LabVIEW MathScript 15 LabVIEW MathScript 3 6 Plotting This chapter explains the basic concepts of creating plots in MathScript Topics e Basic Plot commands Example Plotting Function plot can be used to produce a graph from two vectors x and y The code x Deja 1008 2 jou p y Salm x 2 plor ET produces the following figure of the sine function End of Example Example Plotting Three dimensional graphics can be produced using the functions surf plot3 or mesh BE maslacrescl 102e0 253810 10320 25210 p E ie ere 2D od AE mes OX YE esas 0 10 10 10 0 3 11 Tutorial LabVIEW MathScript 16 LabVIEW MathScript ed ke Eis ylabel bfy zabe 9 4 loneSaline NO hidden off This code produces the following 3D plot End of Example Tutorial LabVIEW MathScript 4Linear Algebra Examples Requires MathScript RT Module Linear algebra is a branch of mathematics concerned with the study of matrices vectors vector spaces also called linear spaces linear maps also called linear transformations and systems of linear equations MathScript are well suited for Linear Algebra 4 1 Vectors Given a vector x x4 x2 Xn Example Vectors Given the following vector The Transpose of vector x xT x1 X2 ses Xn pixn SS X ans 2 3

Download Pdf Manuals

image

Related Search

Related Contents

SkyAlert User`s Guide - Interactive Astronomy    Limpiador en crema  Embedded Systems Trace Solutions  JVC KD-S590 CD Player  Delta UPS - Amplon Family  LaCie 10TB 5big Network  Solución de problemas  Manual do Usuário  Philips SA1215 1GB* Flash audio player  

Copyright © All rights reserved.
Failed to retrieve file