NI Tutorial 7006

Embed Size (px)

Citation preview

  • 8/2/2019 NI Tutorial 7006

    1/151/15 www.ni.com

    Working with .m File Scripts in NI LabVIEW for TextBased Signal Processing, Analysis, and Math

    1.2.3.4.

    1.

    1.

    Overview

    This tutorial provides several step-by-step exercises that introduce you to using NI LabVIEW software to work with .m file scripts for textual math, signal processing, and analysis. It also exploresLabVIEW MathScript, the LabVIEW feature that offers this capability.

    This tutorial does not provide an extensive introduction to the LabVIEW development environment. For an overview of LabVIEW refer to the related tutorial Getting Started with LabVIEW Virtual .Instruments

    This tutorial is only a brief introduction to working with .m file scripts in LabVIEW. Once youve finished, please feel free to explore the environment LabVIEW has numerous features to offer.

    Table of Contents

    Working with .m File Scripts in LabVIEWWorking with the MathScript WindowWorking with the MathScript Node in LabVIEWWorking with the MathScript Node in LabVIEW (Optional)

    Working with .m File Scripts in LabVIEW

    Although LabVIEW is well known as a development environment built around a graphical programming language, it also offers options for working with text-based math programming using .m filescripts. One way to do so is to combine text-based .m file script programming with traditional LabVIEW graphical programming using a script node interface. Script nodes are resizable text entryregions that you can add to your graphical programs.

    One option, the MATLAB script node, connects LabVIEW to The MathWorks, Inc. MATLAB software environment. With this option, you can build custom LabVIEW software that invokes .m file

    scripts from graphical programming. LabVIEW calls on an installed copy of the MATLAB software to execute .m files.

    LabVIEW MathScript is the newest option for working with .m files in LabVIEW. MathScript adds native .m file script support to LabVIEW it does not require additional third-party software. Endusers can benefit from reduced cost and simplified installation. Native .m file script support also simplifies software deployment. Working with the LabVIEW application builder and the MathScript,you can build stand alone executables and DLLs that include functionality defined by .m file scripts.

    Visit for additional information about MathScript including examples, demonstrations, and a user forum.www.ni.com/mathscript

    There are several ways to work with MathScript in LabVIEW. For an interactive interface in which you can load, save, develop, and execute .m file scripts, you can work with the MathScript 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.

    Working with the MathScript Window

    You can complete the exercises in this chapter in approximately 10 minutes.

    Launching LabVIEW

    The window appears when you launch LabVIEW. Use this window to create new VIs, select among the most recently opened LabVIEW files, find examples, and launchLabVIEW Getting Started. You also can access information and resources to help you learn about LabVIEW, such as specific manuals, help topics, and resources on the National Instruments Web site,LabVIEW Help

    ni.com.

    Opening the MathScript Window

    Launch the by choosing the from the menu bar on the window.MathScript Window Tools >> MathScript Window... LabVIEW Getting Started

    The MathScript window provides an interactive interface in which you can enter and execute commands and immediately see results. The MathScript window includes a Command Windowregion in the lower left. Type the following in the and press the key.Command Windowt = 1:10

    :Document Type Tutorial: YesNI Supported: Nov 1, 2009Publish Date

    http://www.ni.com/mathscripthttp://search.ni.com/nisearch/app/main/p/lang/en/pg/1/ap/tech/sn/catnav:tu,ssnav:dznhttp://search.ni.com/nisearch/app/main/p/lang/en/pg/1/ap/tech/sn/catnav:tu,ssnav:dznhttp://www.ni.com/mathscript
  • 8/2/2019 NI Tutorial 7006

    2/152/15 www.ni.com

    1.

    2.

    3.

    1.

    2.

    Note that the result of the command that you just entered will appear in the , found just above the . For this command, the result is an 11-element vector Output Window Command Windowwith elements starting at 1 finishing at 10 with a step of one.Locate the tabs labeled , and to the right of the and near the top. Click on the tab. This part of the display shows a running list of theVariables Script, History Output Window Variablesvariables that you have defined as you work with MathScript.Notice that the list contains an entry for the vector that you defined earlier. Click on the in the list. When you do, you will see the region in the lower right update to show the contents of .t t

    Type the following in the . Press the key at the end of each line.Command Window

    t=0:.1:2*pi;y=sin(t);

    The displays each command after you hit , but does not display the results of the command. The use of the semicolon (;) at the end of each line suppressesOutput Windowcommand output.On the tab, click on the the local variable . As shown in the following figure, modify the view options on the tab to see and modify the contents of the variable as aVariables y Variables ygraph or as numerical elements.

    We have seen how you can work with the to enter commands and see immediate results. We have also explored multiple approaches for visualizing and modifying variableCommand Windowcontents.

    Working with Multi-line Scripts

    Now we will enter multi-line scripts in the to create larger and more involved scripts. We will then run the script and display the result in using several different display formats.Script Editor

  • 8/2/2019 NI Tutorial 7006

    3/153/15 www.ni.com

    1.

    1.

    3.

    Select the tab:Script

    Copy & Paste the following .m file script in the found on the tab. Notice that the script includes comment lines designated by a leading percent (%) character.Script Editor Script

    %Example calculates and graphs the theoretical%BER plots for two types of communication

    %systems (BPSK and QPSK)Eb_over_No_in_dB = [0:14];%Purposes of the x-axis of the plotEb_No=10.^(Eb_over_No_in_dB./10);%PSK is antipodalxant = sqrt(2.*Eb_No);%QPSK is othogonalxorth = sqrt(Eb_No);%Use the erfc function as equivalent to%Q functionQant = 0.5*erfc(xant/sqrt(2));Qorth = 0.5*erfc(xorth/sqrt(2));%Plot the first resultsemilogy(Eb_over_No_in_dB,Qant);%Keeping the same plot in graph%plot the second onegrid on; hold on;semilogy(Eb_over_No_in_dB,Qorth,'r--');v = axis;axis([v(1:2) 10^-6 .1])xlabel('Eb/N0 in dB');ylabel('Probability of bit error')hold off;legend('Antipodal','Orthogonal')

    Click on Run icon to execute the script.

    Note that the example script plots the theoretical value of bit error rate (BER) from a digital communication system with two different digital modulation schemes.

  • 8/2/2019 NI Tutorial 7006

    4/154/15 www.ni.com

    1.

    2.

    3.

    1.2.

    1.

    This example invokes several built-in functions for math, graph formatting, and other tasks. MathScript includes over 700 built-in functions for a variety of tasks covering categories such as matrixdefinition, linear algebra, approximation, audio, bitwise operations, Boolean operations, utility commands, relational operators, data acquisition, digital signal processing, digital filter design, digitalfilter implementation, combinatorial geometry, interfacing with shared libraries(DLLs), linear algebra, linear systems, matrix operations, set membership, modeling/prediction, ODE, optimization,plotting, polynomial operations, programming constructs, resampling functions, set operations, string manipulation, support functions, time/date functions, timing functions, transforms, trigonometricfunctions, vector analysis, waveform generation, and window generation.

    In addition to the built-in functions, you can also work with user-defined .m file script functions.

    Clear any script lines that currently occupy the editor window. Type or Copy & Paste the following script into the editor window. The script specifies a user-defined function called that rad2degconverts an input parameter rad to degrees and returns the result deg.

    function deg = rad2deg(rad)

    % This is a Comment% This function converts from radians to degrees.deg = rad.*180./pi;Save and compile the new script by pressing the Save As button. Use the file name and place it in the directory. This directory is the default pathrad2deg.m My Documents\LabVIEW Datathat MathScript searches to locate user-defined function definitions.

    Tip: You can change the MathScript search path using the path command or by setting a software preference found under the menu File >> PreferencesWorking in the , type each of the following commands, pressing the key after each entry.Command Window

    Type This Description of the Result

    rad2deg(pi)Invokes the user-defined function that you haddefined above

    help rad2degReturns the first commented paragraph as thedocumentation for your user-defined function

    rad2deg(linspace(0,pi,10))Invokes the user-defined function that you haddefined above with a function call (linspace) as aparameter

    As you can see, the user-defined function is now available as a function that you canrad2degcall from your scripts.

    For more help related to working with user-defined .m file script functions type in the helpand search for .Command Window MathScript Function Syntax

    This concludes the walk-through material related to working with the . TheMathScript windownext section relates some MathScript tips and guidelines for trying out your own .m file scriptswith MathScript.

    MathScript Tips and Tricks

    With the cursor in the , you can use the on the keyboard to scroll among the commands history.Command Window Up/Down arrowsRight click on the variable display area in the tab and select from the pop-up menu in order to create a pop-up window that you can resize in order to optimizeVariables Undock Windowyour view of variable contents.

    Try Out Your .m file Scripts

    You can Cut & Paste scripts into the through the online evaluation version of LabVIEW.MathScript window Script Editor

  • 8/2/2019 NI Tutorial 7006

    5/155/15 www.ni.com

    2.3.

    1.2.

    1.

    2.

    3.4.

    To try out your .m file scripts locally, you can work with the installable evaluation edition of LabVIEW found . hereMathScript supports many, but not all .m file scripts. Often, slight modifications help you to successfully execute .m file scripts with MathScript. The following guidelines can help determinewhether you can expect your scripts to work without changes.

    MathScript includes built-in functionality that is similar to that found in a major competitive technical computing software environment that works with .m file script. MathScript also includesbuilt-in functionality that is similar to that found in an add-on signal processing toolbox available from a major competitive technical computing software environment.

    MathScript does not support calling functions from third-party software add-on toolboxes.

    You can break up longer multiline scripts into shorter scripts in order to improve compile time. You can do so by creating user-defined functions.

    MathScript does not support data types that include integer (int), sparse matrices, cell arrays, structures, handle graphics, and matrices with more than two dimensions.

    MathScript does not support recursive function calls.

    Working with the MathScript Node in LabVIEW

    Have you ever wanted to interactively change the value of a parameter and immediately see the response? Have you ever wanted to test your .m file script algorithm with real acquired data?

    With NI LabVIEW, you can choose the most effective syntax for technical computing whether you are developing algorithms, exploring signal processing concepts, or analyzing results. You cancombine LabVIEW graphical programming with LabVIEW MathScript, a math-oriented textual programming language that uses .m file script syntax.

    You can work with LabVIEW MathScript through either of two interfaces, the LabVIEW MathScript window or the MathScript node. You can use the MathScript node to combine textual algorithmswith LabVIEW graphical programming. Doing so, you can instrument your .m file scripts by adding knobs, slides, buttons, graphics, and other controls and indicators. To work entirely withtext-based .m file script programming, refer to the first section of this document for information about the LabVIEW MathScript window.

    In this section, we will build an example in LabVIEW to highlight the benefits of combining text-based .m scripts with LabVIEW graphical programming.

    Create the User Interface

    The following steps show you how to create controls and indicators in the LabVIEW front panel.

    Launch .LabVIEWFrom the window, select or click the link to create a new VI.LabVIEW Getting Started File >> New VI Blank VI

    On the front panel of the VI, select to display the palette. Move the cursor over the icons on the palette to locate the palette. When youView >> Controls Palette Controls Modern Graphmove the cursor over icons on the palette, the name of the subpalette, control, or indicator appears in a tip strip below the icon.ControlsFrom the palette, add a new indicator to the front panel. Double click the new text label edit it and change the name of the control toGraph Waveform Graph Waveform Graph Signal

    .Samples Add a second indicator to the front panel. Double-click on the graph label and change it to .Waveform Graph FFT Result Show the block diagram of this VI , which should resemble the one below.

    http://digital.ni.com/demo.nsf/websearch/14F9CE475127ADE786256AC60070926Chttp://digital.ni.com/demo.nsf/websearch/14F9CE475127ADE786256AC60070926C
  • 8/2/2019 NI Tutorial 7006

    6/156/15 www.ni.com

    1.2.

    1.

    2.

    3.

    4.

    Display the if it isnt already shown by selecting .Functions Palette View >> Functions PaletteNavigate to palette and click on . Move your mouse to the block diagram, then left-click and drag the mouse to place the onProgramming >> Structures MathScript node MathScript nodethe block diagram.There are two ways to enter .m file commands in the . You can either type commands directly in the node or import an .m file script from an existing .m file on your computer.MathScript node

    Cut & Paste the following .m file script into the .MathScript node

    fftresult=abs(fft(signalin));fftresult=fftresult(1:end/2);

    You can also load and save .m file scripts from files by right-click ing on the border of the and selecting or from the shortcut menu.MathScript node Import ExportThe command

    fftresult=abs(fft(signalin);

    does the following:

    Calls the built-in function fft to apply a Fast Fourier Transform to an input vector called signalin. Calls the built-in function abs to calculate the absolute value of the result of the fft function. Assigns the result to a variable called fftresult.

    The command

    fftresult=fftresult(1:end/2);

    assigns the fftresult variable to the first half of the data that is the result of the analysis of the previous line. The reason for this step is that the result of applying an FFT to a real-valued signalis symmetric, so it is common to only examine half of the result.

    Next, you will define the interface between the text-based world of .m file script and graphical programming by right-clicking on the boundaries of the to set input andMathScript nodeoutputs.Right-click the left edge of the and select from the shortcut menu. Type in the input terminal to add an input for the variable in the script.MathScript node Add Input signalin signalinEntering signalin here associates this terminal with the variable in the .m file script and enables the .m file script to receive new values for .signalin signalinRight-click on the right edge of the (blue line) and select from the shortcut menu. Type in the output terminal to add an output for the variable inMathScript node Add Output fftresult fftresult the script.The previous step makes the result from the .m file script available as an output that can be accessed by the rest of your LabVIEW application.Right-click the output terminal and select from the shortcut menu to specify the data type of the output variable.fftresult Choose Data Type >> 1D-Array >> DBL 1D fftresult

  • 8/2/2019 NI Tutorial 7006

    7/157/15 www.ni.com

    1.

    1.2.

    3.

    1.2.

    The previous step defines the data type of the output.MathScript node

    Add a loop from so that it encloses all of the elements that you have added so far to the block diagram.While Programming >> Structures

    The loop permits the acquisition and analysis in your code to run continuously.While

    Right-click on the conditional terminal of the loop and select to add a button to the front panel.Create Control Stop Add the Express VI from the subpalette to the inside of the loop, left of the .Simulate Signal Express While MathScript node

    The will simulate acquiring data from a measurement device.Simulate Signal VIChoose the following selections in the configuration window and press .Simulate Signal OK

    Signal

    Signal type = Square

    Frequency = 50 Hz

    Add noise = checked

    Noise type = Uniform White Noise

    Noise amplitude = 0.3

    Timing

    Samples per second (Hz) = 10000

    Automatic = checked

    Connect the data output from the VI to the graph to display the synthesized signal.Simulate Signal Signal Samples Add a Express VI to the diagram. Click to choose the default settings for that VI and close its configuration dialog.Convert from Dynamic Data OK

  • 8/2/2019 NI Tutorial 7006

    8/158/15 www.ni.com

    1.2.3.

    1.

    1.2.3.

    The Express VI converts data from the Dynamic Datatype to a 1D array of scalars, which is a datatype supported by the MathScript nodeConvert from Dynamic Data

    Wire the output from the Express VI to the input of the Express VI.Simulate Signal Convert from Dynamic DataWire the output of the VI to the input on the .Convert from Dynamic Data signalin MathScript nodeWire the output on the right side of the to the graph terminal.fftresult MathScript node FFT Result

    Return to the front panel and press the button to start the application. When you run the VI, you can see the live signal on the left graph and the results of the analysis on the right.Run

    Stop the VI and return to the block diagram. Add a Express VI from the palette inside the loop.Filter Express >> Signal Analysis WhileChoose the following selections in the configuration window and press .Filter OK

    Filter type = smoothing

    Moving average = Triangular

    Half-width moving average = 7

  • 8/2/2019 NI Tutorial 7006

    9/159/15 www.ni.com

    1.2.

    1.

    LabVIEW provides you with the flexibility to implement signal processing and analysis either graphically or textually.

    Wire the output of the VI to the input on the VI.Simulate Signal Signal Filter Right-click on the output on the VI and chooseFiltered Signal Filter Create >> Graph

    on the pop-up menu to create a to display the filtered signal.Indicator Waveform GraphWhen you complete your VI, it should resemble the figure below.

    Return to the front panel and press the button to start the application.Run

  • 8/2/2019 NI Tutorial 7006

    10/1510/15 www.ni.com

    1.2.

    3.

    1.

    1.2.

    Working with the MathScript Node in LabVIEW (Optional)

    In this optional section, we will build a more involved example in LabVIEW that displays an RF antenna pattern for a dish antenna in linear (XY) and polar plots. The example shows how you caneasily build a custom user interface to add interactivity to an algorithm defined with an .m file script using a MathScript node. The example adds an input control to set the amplitude/lambda inputparameter of the algorithm.

    Create the User Interface

    Launch and create a blank VI.LabVIEWOn the front panel of the VI, select to display the palette. Move the cursor over the icons on the palette to locate the palette. When youView >> Controls Palette Controls Modern Numericmove the cursor over icons on the palette, the name of the subpalette, control, or indicator appears in a tip strip below the icon.ControlsClick the icon to display the subpalette. Move the cursor over the icons on the palette to locate the control. We will rely on this control to set the size andNumeric Numeric Numeric Knobwavelength of the antenna. Click the icon and drag it to the front panel.Knob

    Double-click the text label on the control to edit it. Change the name of the control to .Knob Knob Amplitude/lamda

    Click the icon to display the palette. This graph will show a linear display of the RF antenna pattern.Graph GraphMove the cursor over the icons on the palette to locate the . Click the icon and drag it to the front panel. You can display the results of an application by usingGraph XY Graph XY Graphindicators, charts, and other graphical displays on the front panel of a VI.

  • 8/2/2019 NI Tutorial 7006

    11/1511/15 www.ni.com

    1.

    1.

    2.

    1.2.3.4.

    Move the cursor over the icons on the palette and then to the subpalette to locate the indicator. Click the indicator icon and drag it to the front panel.Graph Controls Polar Plot Polar PlotThis indicator will show the RF antenna pattern as a function of angle.

    Select from the menu to display the block diagram of the VI. Building a block diagram is similar to building a front panel. When you place objects on theWindow >> Show Block Diagramfront panel, LabVIEW creates terminals for those objects on the block diagram. You can wire data in or out of the block diagram terminals to display data on the user interface or to use user input values in your application.Locate the controls and indicators we just created on the front panel. Move the and the to the right side of the block diagram. On this window we will connect blocksPolar Plot XY Graphtogether to program the results of the RF antenna pattern.

    Add an .m file Script to the MathScript Node

    On the block diagram, select to display the palette.View >> Functions Palette FunctionsMove the cursor over the icons on the palette to locate the palette.Programming StructuresClick the icon to display the palette. Move the cursor over the icons on the palette to locate the .Structures Structures Structures MathScript nodeClick the icon. On the block diagram, click and drag the mouse in a rectangular shape to place the .MathScript node MathScript node

  • 8/2/2019 NI Tutorial 7006

    12/1512/15 www.ni.com

    1.

    2.

    1.2.3.4.

    1.2.

    Cut & Paste the code below inside the . This is the actual code to process the gain of the antenna at different angles.MathScript node

    %Create angle vector in radianstheta = linspace(-pi/2,pi/2,1000);u = 2*pi*a*sin(theta);%initialize matrixE = ones(size(u));%Get index of non-zero valuesi = find(u);%Evaluate Antenna patern equationE(i) = pi*a^2*abs(2*besselj(1,u(i))./(u(i)));%change theta to degrees units for polar plotOut=theta.*180./pi;Right-click the MathScript node frame and select from the shortcut menu. This will create interaction with the .m file script and our controls.Add Input

    Type in the input terminal to add an input for the variable inside the script. This will be the MathScript variable we update with a LabVIEW control.a aRight-click the frame and select from the shortcut menu. This will create interaction between .m file script and LabVIEW indicators.MathScript node Add OutputType in the output terminal to add an output for the variable inside the script. This output is the angle vector for plotting purposes.Out OutRight-click the output terminal and select from the shortcut menu to specify the data type of the output variable.Out Choose Data Type >> 1D-Array >> DBL 1D Out

    Repeat the previous step for the variable. This variable is the gain output at different angles.EWe will now build the following part of the . You can find the in the palette. This combines the X and Y components of our regular plot.Block Diagram Bundle VI Programming >> Cluster

  • 8/2/2019 NI Tutorial 7006

    13/1513/15 www.ni.com

    1.2.3.

    4.

    1.

    In the next several steps, we will work to complete the as shown on the following figure:Block Diagram

    Place a found under . Click and drag to create the small region.For Loop Programming >> Structures >> For LoopPlace a from the palette inside the .Bundle VI Programming >> Cluster For LoopConnect the terminals as shown in the previous figure. The squares in the border of the mean auto indexing and its going to process each element separately. This is because theFor Loop

    VI requires 1D array of clusters of two elements.Polar PlotCreate a control for the input of the VI by right-clicking on the input on the VI and choosing from the pop-up menu.Polar attributes Polar Plot Polar attributes Polar Plot Create >> Control

    Go to the front panel and set the control to 2. Set the parameters of theAmplitude/lamda Polar to show a log scale and display only the left half of the plot.Plot

  • 8/2/2019 NI Tutorial 7006

    14/1514/15 www.ni.com

    1.2.3.

    1.

    Run the program. You will notice the graph changing and then the program will stop automatically.Next, return to the and add a to run these actions continuously.Block Diagram While LoopEncircle all elements on the block diagram with an express under .While Loop Express >> Execution Control >> While Loop

    Run the VI. The results represent the gain of a dish antenna at different angles.

    MATLAB is a registered trademark of The MathWorks, Inc.

  • 8/2/2019 NI Tutorial 7006

    15/15

    LegalThis tutorial (this "tutorial") was developed by National Instruments ("NI"). Although technical support of this tutorial may be made available by National Instruments, the content in this tutorial maynot be completely tested and verified, and NI does not guarantee its quality in any way or that NI will continue to support this content with each new revision of related products and drivers. THISTUTORIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND AND SUBJECT TO CERTAIN RESTRICTIONS AS MORE SPECIFICALLY SET FORTH IN NI.COM'S TERMS OF USE (

    ).http://ni.com/legal/termsofuse/unitedstates/us/

    http://ni.com/legal/termsofuse/unitedstates/us/http://ni.com/legal/termsofuse/unitedstates/us/