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

Publish Date: Nov 01, 2009 | 3 Ratings | 5.00 out of 5 |  PDF

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 explores LabVIEW 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 you’ve finished, please feel free to explore the environment – LabVIEW has numerous features to offer.

Table of Contents

  1. Working with .m File Scripts in LabVIEW
  2. Working with the MathScript Window
  3. Working with the MathScript Node in LabVIEW
  4. Working with the MathScript Node in LabVIEW (Optional)

1. 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 file scripts. 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 entry regions 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. End users 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 www.ni.com/mathscript for additional information about MathScript including examples, demonstrations, and a user forum.

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. 

Back to Top

2. Working with the MathScript Window

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

Launching LabVIEW

The LabVIEW Getting Started window appears when you launch LabVIEW. Use this window to create new VIs, select among the most recently opened LabVIEW files, find examples, and launch LabVIEW Help. 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, ni.com.

Opening the MathScript Window

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

 

  1. 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 Window region in the lower left. Type the following in the Command Window and press the <Enter> key.
    t = 1:10

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

  1. Type the following in the Command Window. Press the <Enter> key at the end of each line.

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

    The Output Window displays each command after you hit <Enter>, but does not display the results of the command. The use of the semicolon (‘;’) at the end of each line suppresses command output.
  2. On the Variables tab, click on the the local variable y. As shown in the following figure, modify the view options on the Variables tab to see and modify the contents of the y variable as a graph or as numerical elements.

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

Working with Multi-line Scripts

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

  1. Select the Script tab:

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

    %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 plot
    Eb_No=10.^(Eb_over_No_in_dB./10);
    %PSK is antipodal
    xant = sqrt(2.*Eb_No);
    %QPSK is othogonal
    xorth = sqrt(Eb_No);
    %Use the erfc function as equivalent to
    %Q function
    Qant = 0.5*erfc(xant/sqrt(2));
    Qorth = 0.5*erfc(xorth/sqrt(2));
    %Plot the first result
    semilogy(Eb_over_No_in_dB,Qant);
    %Keeping the same plot in graph
    %plot the second one
    grid 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')

  2. 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.

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 matrix definition, linear algebra, approximation, audio, bitwise operations, Boolean operations, utility commands, relational operators, data acquisition, digital signal processing, digital filter design, digital filter 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, trigonometric functions, 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.

  1. 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 rad2deg that converts 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;
  2. Save and compile the new script by pressing the Save As button. Use the file name rad2deg.m and place it in the My Documents\LabVIEW Data directory. This directory is the default path that 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 >> Preferences…
  3. Working in the Command Window, type each of the following commands, pressing the <Enter> key after each entry.
Type This Description of the Result
rad2deg(pi) Invokes the user-defined function that you had
defined above
help rad2deg Returns the first commented paragraph as the
documentation for your user-defined function
rad2deg(linspace(0,pi,10)) Invokes the user-defined function that you had
defined above with a function call (“linspace”) as a
parameter

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

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

This concludes the walk-through material related to working with the MathScript window. The
next section relates some MathScript tips and guidelines for trying out your own .m file scripts
with MathScript.

MathScript Tips and Tricks

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

 

Try Out Your .m file Scripts

  1. You can Cut & Paste scripts into the MathScript window Script Editor through the online evaluation version of LabVIEW.
  2. To try out your .m file scripts locally, you can work with the installable evaluation edition of LabVIEW found here.
  3. MathScript 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 determine whether 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 includes built-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.

Back to Top

3. 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 can combine 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 algorithms with 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 with text-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.

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

  1. On the front panel of the VI, select View >> Controls Palette to display the Controls palette. Move the cursor over the icons on the Modern palette to locate the Graph palette. When you move the cursor over icons on the Controls palette, the name of the subpalette, control, or indicator appears in a tip strip below the icon.
  2. From the Graph palette, add a new Waveform Graph indicator to the front panel. Double click the new Waveform Graph text label edit it and change the name of the control to Signal Samples.
  3. Add a second Waveform Graph indicator to the front panel. Double-click on the graph label and change it to FFT Result.
  4. Show the block diagram of this VI <Control-E>, which should resemble the one below.

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

  1. 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-clicking on the border of the MathScript node and selecting Import or Export from the shortcut menu.
    The 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 signal is 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 MathScript node to set input and outputs.
  2. Right-click the left edge of the MathScript node and select Add Input from the shortcut menu. Type signalin in the input terminal to add an input for the signalin variable in the script.
    Entering signalin here associates this terminal with the signalin variable in the .m file script and enables the .m file script to receive new values for signalin.
  3. Right-click on the right edge of the MathScript node (blue line) and select Add Output from the shortcut menu. Type fftresult in the output terminal to add an output for the fftresult variable in 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.
  4. Right-click the fftresult output terminal and select Choose Data Type >> 1D-Array >> DBL 1D from the shortcut menu to specify the data type of the fftresult output variable.

 

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

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

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

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

    The Simulate Signal VI will simulate acquiring data from a measurement device.
  3. Choose the following selections in the Simulate Signal configuration window and press 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

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

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

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

  1. Return to the front panel and press the Run 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.

  1. Stop the VI and return to the block diagram.
  2. Add a Filter Express VI from the Express >> Signal Analysis palette inside the While loop.
  3. Choose the following selections in the Filter configuration window and press OK.
    • Filter type = smoothing
    • Moving average = Triangular
    • Half-width moving average = 7

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

  1. Wire the output of the Simulate Signal VI to the Signal input on the Filter VI.
  2. Right-click on the Filtered Signal output on the Filter VI and choose Create >> Graph
    Indicator on the pop-up menu to create a Waveform Graph to display the filtered signal.
    When you complete your VI, it should resemble the figure below.

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

 

Back to Top

4. 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 can easily 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 input parameter of the algorithm.

Create the User Interface

  1. Launch LabVIEW and create a blank VI.
  2. On the front panel of the VI, select View >> Controls Palette to display the Controls palette. Move the cursor over the icons on the Modern palette to locate the Numeric palette. When you move the cursor over icons on the Controls palette, the name of the subpalette, control, or indicator appears in a tip strip below the icon.
  3. Click the Numeric icon to display the Numeric subpalette. Move the cursor over the icons on the Numeric palette to locate the Knob control. We will rely on this control to set the size and wavelength of the antenna. Click the Knob icon and drag it to the front panel.

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

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

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

  1. Select Window >> Show Block Diagram 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 the front 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.
  2. Locate the controls and indicators we just created on the front panel. Move the Polar Plot and the XY Graph to the right side of the block diagram. On this window we will connect blocks together to program the results of the RF antenna pattern.

Add an .m file Script to the MathScript Node

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

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

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

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

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

 

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

  1. Place a For Loop found under Programming >> Structures >> For Loop. Click and drag to create the small region.
  2. Place a Bundle VI from the Programming >> Cluster palette inside the For Loop.
  3. Connect the terminals as shown in the previous figure. The squares in the border of the For Loop mean “auto indexing” and its going to process each element separately. This is because the Polar Plot VI requires 1D array of clusters of two elements.
  4. Create a control for the Polar attributes input of the Polar Plot VI by right-clicking on the Polar attributes input on the Polar Plot VI and choosing Create >> Control from the pop-up menu.

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

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

 

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

 

MATLAB® is a registered trademark of The MathWorks, Inc.

Back to Top

Bookmark & Share

Ratings

Rate this document

Answered Your Question?
Yes No

Submit