1. Working with .m Files in LabVIEW
Although LabVIEW is a development environment built around a graphical programming language, LabVIEW also allows you to create .m files and work with text-based math. One way to work with text-based math in LabVIEW is through a script node interface. Script nodes combine text-based .m files with traditional LabVIEW graphical programming. Script nodes are resizable text-entry regions you can add to LabVIEW block diagrams.
One type of script node, the MATLAB script node, calls the MATLAB® software to execute scripts. You must have a licensed copy of the MATLAB software 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.
You also can create scripts in LabVIEW with LabVIEW MathScript. LabVIEW MathScript is a text-based language you can use to write functions and scripts for use in the LabVIEW MathScript Window or MathScript Node. MathScript Nodes can process many of your text-based scripts created in a MATLAB or compatible environment. However, because the MathScript RT Module engine does not support all functions supported by the MATLAB software, some functions in your existing scripts might not be supported. You can implement such functions with a Formula Node or another script node. You can use the LabVIEW Application Builder and MathScript to build stand-alone applications and shared libraries that include functionality defined in .m files.
You can interact with MathScript in several different ways. Use the LabVIEW MathScript Window for an interactive interface in which you can load, save, develop, and execute .m file scripts. Use the MathScript Node to utilize the graphical programming environment in LabVIEW and to deploy .m file scripts as part of a stand-alone application.
The following section offers a brief walk-through of the LabVIEW MathScript Window. Later sections in this tutorial discuss the MathScript Node.
MATLAB® is a registered trademark of The MathWorks, Inc. All other trademarks are the property of their respective owners
2. Working in the LabVIEW MathScript Window
The Getting Started window appears when you launch LabVIEW. Use this window to create new VIs and projects, select among the most recently opened LabVIEW files, find examples, and launch the 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.
Opening the LabVIEW MathScript Window
- Select Tools»MathScript Window to display the LabVIEW MathScript Window.
- The LabVIEW MathScript Window includes a Command Window in the lower left corner. Enter the following command in the Command Window and press the <Enter> key:
t = 1:10
- Notice that the result of the command you entered appears in the Output Window, located just above the Command Window. The result of this command is a vector of ten elements, where the elements start at 1 and end at 10 with a step size of 1.
- Locate the tabs labeled Variables, Script, and History at the top right of the LabVIEW MathScript Window. Click the Variables tab to display the Variables page. This page displays a list of all variables you define and previews variables that you select.
- Notice that the variable list contains an entry for the t vector you defined in step 2. Click the t in the variable list to display the contents of t in the Preview Pane located in the lower right corner of the LabVIEW MathScript Window.
- Enter the following commands in the Command Window. Press the <Enter> key at the end of each line.
After you press the <Enter> key, LabVIEW displays each command in the Output Window. LabVIEW does not display the output for each command because the semicolon at the end of each line directs LabVIEW to suppresses the output.
- On the Variables page, click the local variable y. Then modify the view options on the Variables page to view the contents of the y variable as a graph or as numerical elements, as shown in the following figure. You also can use these different views to modify the contents of the variable.
Working with Multi-Line Scripts
The previous exercise demonstrated how to use the Command Window to enter commands and view the output for these commands. The exercise also showed how to view and modify the contents of variables. The following exercise shows how to use the Script Editor to enter multi-line scripts and create larger, more involved scripts. Complete the following steps to create a multi-line script, run the script, and then display the results in several different display formats.
- Click the Script tab to display the Script page.
- Copy and paste the following file script into the Script Editor on the Script page. Notice the script includes percent signs (%) that precede lines of comments. Use these comments to include help documentation for the script.
% This 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
% PSK is antipodal
xant = sqrt(2.*Eb_No);
% QPSK is orthogonal
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
% Keep the same plot in graph
% plot the second one
grid on; hold on;
v = axis;
axis([v(1:2) 10^-6 .1])
xlabel('Eb/N0 in dB');
ylabel('Probability of bit error')
- Click the Run button to execute the script, as shown in the following figure.
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 built-in functions for a variety of tasks, including categories such as advanced math, approximation, audio, basic math, 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 MathScript functions, you also can define functions in .m files. Complete the following steps to define a function in a .m file.
- Delete all commands on the Script Editor page. Then copy and paste the following script into the Script Editor. The script defines a function named rad2deg. This function converts an input parameter rad to degrees and returns the result in the deg output.
function deg = rad2deg(rad)
% This is a Comment
% This function converts from radians to degrees.
deg = rad.*180./pi;
- Click the Save button to save the function as rad2deg.m in the LabVIEW Data directory. By default, LabVIEW searches the LabVIEW Data directory for user-defined functions and user-defined scripts.
NOTE: Use the MathScript: Search Paths Options page to configure the default search path list for MathScript. Select File»LabVIEW MathScript Properties to display the LabVIEW MathScript Properties dialog box and select MathScript: Search Paths from the Category list to display this page.
- In the Command Window, enter the following commands and press the <Enter> key after each command.
Result of the Command
Invokes the user-defined function you previously defined.
Returns the first commented paragraph as the help documentation for the user-defined function.
Invokes the user-defined function that you previously defined with a function call (“linspace”) as a parameter.
The user-defined function rad2deg now is available as a function you can call from scripts.
3. MathScript Tips
This section contains a few tips for using the LabVIEW MathScript Window. The following tips might be useful as you work in the LabVIEW MathScript Window.
- Place the cursor in the Command Window and use the Up and Down arrow keys on the keyboard to scroll through the command history.
- Right click the Preview Pane on the Variables page and select Undock Window from the shortcut menu to display the variable in a separate window that you can resize.
4. Trying Out .m File Scripts
There are several online and local options that allow you to test your user-defined scripts in MathScript. Refer to the Use Fully Featured LabVIEW MathScript Today Developer Zone document (linked below) for more information about these options.
5. Using the MathScript Node, Part I
Have you ever wanted to interactively change the value of a parameter and immediately see the response? Have you ever wanted to test the algorithm in a user-defined script with real acquired data?
With 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.
You can use the MathScript Node to combine textual algorithms with LabVIEW graphical programming. You then can use knobs, slides, buttons, graphics, and other controls and indicators to instrument .m file scripts.
Creating the User Interface
This section describes how to build an example in LabVIEW that highlights the benefits of combining text-based MathScripts with LabVIEW graphical programming.
Complete the following steps to create controls and indicators in a LabVIEW front panel window.
- In the Getting Started window, select File»New VI or select Blank VI from the New section to create a new VI.
- Add a Waveform Graph indicator to the front panel. Double-click the Waveform Graph text label to edit the label. Change the name of the label to Signal Samples.
- Add a second Waveform Graph indicator to the front panel. Change the label to FFT Result.
- Switch to the block diagram and place a MathScript Node on the block diagram.
NOTE: You can enter commands in the MathScript Node in one of two ways. First, you can enter commands directly in the node. Second, you can import the script from an existing .m file.
- Copy and paste the following script into the MathScript Node:
You also can load and save scripts from .m files by right-clicking the border of the MathScript Node and selecting Import or Export from the shortcut menu.
The first command line in the previous script does the following:
- Calls the fft function to apply a fast Fourier transform (FFT) to an input vector called signalin.
- Calls the abs function to calculate the absolute value of the result of the fft function.
- Assigns the result to a variable called fftresult.
The second command line in the previous script 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 examine only half of the result.
- Right-click the left side of the MathScript Node frame and select Add Input from the shortcut menu. Enter signalin in the input terminal to add an input for the signalin variable in the script.
- Right-click the right side of the MathScript Node frame and select Add Output from the shortcut menu. Enter fftresult in the output terminal to add an output for the fftresult variable in the script.
- 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.
- Add a While Loop to the block diagram so that the loop encloses all the elements on the block diagram, as shown in the following block diagram. The While Loop allows the acquisition and analysis in the code to run continuously.
- Right-click the conditional terminal of the While Loop and select Create Control to add a Stop button to the front panel.
- Add the Simulate Signal Express VI to the block diagram, inside the While Loop to the left of the MathScript Node. The Simulate Signal Express VI simulates acquiring data from a measurement device.
- Choose the following configuration options in the Simulate Signal dialog box and then click the OK button.
- Signal type = Square
- Frequency = 50 Hz
- Add noise = checked
- Noise type = Uniform White Noise
- Noise amplitude = 0.3
- Samples per second (Hz) = 10000
- Automatic = checked
- Connect the data output from the Simulate Signal Express VI to the Signal Samples graph to display the synthesized signal.
- Add a Convert from Dynamic Data Express VI to the block diagram. Click the OK button to choose the default settings for the VI and close the configuration dialog box.
The Convert from Dynamic Data Express VI converts data from the dynamic data type to a 1D array of scalars, which is a data type that the MathScript Node supports.
- Wire the output from the Simulate Signal Express VI to the input of the Convert from Dynamic Data Express VI.
- Wire the output of the Convert from Dynamic Data VI to the signalin input of the MathScript Node.
- Wire the fftresult output on the right side of the MathScript Node to the FFT Result graph terminal. The block diagram should resemble the following screenshot.
- Switch to the front panel and click the Run button to run the VI. LabVIEW displays the live signal in the graph on the left side of the front panel and the results of the analysis in the graph on the right side of the front panel.
- Click the STOP button and then switch to the block diagram.
- Add a Filter Express VI to the block diagram inside the While Loop.
- Choose the following selections in the Filter dialog box and click the OK button.
- Filter type = smoothing
- Moving average = Triangular
- Half-width moving average = 7
- Wire the output of the Simulate Signal Express VI to the Signal input of the Filter VI.
- Right click the Filtered Signal output of the Filter VI and select Create»Graph Indicator from the shortcut menu to create a waveform graph. This graph displays the filtered signal. The block diagram should resemble the following screenshot.
- Switch to the front panel and click the Run button to run the VI.
6. Using the MathScript Node, Part II
This section includes an example of building a more complicated VI that displays an RF antenna pattern for a dish antenna in linear (XY) and polar plots. The example shows how to build a custom user interface to add interactivity to an algorithm you define in a script in a .m file using a MathScript Node. The example adds a control input to set the amplitude/lambda input parameter of the algorithm.
Creating the User Interface
- Open a new VI.
- Add a knob control to the front panel. You can use this control to set the size and wavelength of the antenna.
- Change the name of the Knob control to Amplitude/lambda.
- Add an XY graph 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.
- Add a polar plot indicator to the front panel. You can use this indicator to show the RF antenna pattern as a function of the angle.
- Switch to the block diagram and locate the controls and indicators you created on the front panel. Move the polar plot indicator and the XY graph to the right side of the block diagram, as shown in the following screenshot.
Adding a Script to a MathScript Node
- Add a MathScript Node to the block diagram.
- Copy and paste the following script into the MathScript Node. This script processes 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 pattern equation
E(i) = pi*a^2*abs(2*besselj(1,u(i))./(u(i)));
% change theta to degrees units for polar plot
- Right-click the left border of the MathScript Node and select Add Input from the shortcut menu.
- Enter a in the input to add an input for the a variable in the script.
- Right-click the right border of the MathScript Node and select Add Output from the shortcut menu.
- Enter Out in the output terminal to add an output for the Out variable in the script. This variable represents the angle vector for plotting purposes.
- 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.
- Repeat the steps 5 through 7 for the E variable. This variable represents the gain output at different angles.
- Add a Bundle function to the block diagram to combine the X and Y components of the regular plot, as shown in the following block diagram.
- Add a For Loop to the block diagram.
- Place a Bundle function inside the For Loop.
- Connect the input and output terminals. The squares in the border of the For Loop indicate the loop is set to auto index, or process each input element separately.
- Right click the Polar attributes input of the Polar Plot VI and select Create»Control from the shortcut menu.
- Switch to the front panel and set the Amplitude/lambda control to 2. Configure the parameters of the polar plot to show a Log scale and display only the right half of the plot, as shown in the following front panel.
- Run the VI. The graph updates and then the VI automatically stops.
- Switch to the block diagram. Add an express While Loop that encircles all elements on the block diagram, as shown in the following screenshot.
- Run the VI. The results represent the gain of a dish antenna at different angles.
7. Related Links