# Connexions

You are here: Home » Content » Lab 2: LabVIEW MathScript and Hybrid Programming

### Recently Viewed

This feature requires Javascript to be enabled.

# Lab 2: LabVIEW MathScript and Hybrid Programming

## Arithmetic Operations

There are four basic arithmetic operators in .m files:

+ addition

- subtraction

* multiplication

/ division (for matrices, it also means inversion)

The following three operators work on an element-by-element basis:

.* multiplication of two vectors, element-wise

./ division of two vectors, element-wise

.^ raising all the elements of a vector to a power

As an example, to evaluate the expression a3+bd4ca3+bd4c size 12{a rSup { size 8{3} } + sqrt { ital "bd"} - 4c} {} , where a=1.2a=1.2 size 12{a=1 "." 2} {}, b=2.3b=2.3 size 12{b=2 "." 3} {}, c=4.5c=4.5 size 12{c=4 "." 5} {}and d=4d=4 size 12{d=4} {}, type the following commands in the Command Window to get the answer (ans) :

>> a=1.2;

>> b=2.3;

>> c=4.5;

>> d=4;

>> a^3+sqrt(b*d)-4*c

ans =

-13.2388

Note the semicolon after each variable assignment. If the semicolon is omitted, the interpreter echoes back the variable value.

## Vector Operations

Consider the vectors x =[x1,x2,...,xn]=[x1,x2,...,xn] size 12{ {}= $x rSub { size 8{1} } ,x rSub { size 8{2} } , "." "." "." ,x rSub { size 8{n} }$ } {}and y =[y1,y2,...,yn]=[y1,y2,...,yn] size 12{ {}= $y rSub { size 8{1} } ,y rSub { size 8{2} } , "." "." "." ,y rSub { size 8{n} }$ } {}. The following operations indicate the resulting vectors:

x*.y =[x1y1,x2y2,...,xnyn]=[x1y1,x2y2,...,xnyn] size 12{ {}= $x rSub { size 8{1} } y rSub { size 8{1} } ,x rSub { size 8{2} } y rSub { size 8{2} } , "." "." "." ,x rSub { size 8{n} } y rSub { size 8{n} }$ } {}

x./y =x1y1,x2y3,...,xnyn=x1y1,x2y3,...,xnyn size 12{ {}= left [ { {x rSub { size 8{1} } } over {y rSub { size 8{1} } } } , { {x rSub { size 8{2} } } over {y rSub { size 8{3} } } } , "." "." "." , { {x rSub { size 8{n} } } over {y rSub { size 8{n} } } } right ]} {}

x.^p =x1p,x2p,...,xnp=x1p,x2p,...,xnp size 12{ {}= left [x rSub { size 8{1} } rSup { size 8{p} } ,x rSub { size 8{2} } rSup { size 8{p} } , "." "." "." ,x rSub { size 8{n} } rSup { size 8{p} } right ]} {}

Note that because the boldfacing of vectors/matrices are not used in .m files, in the notation adopted in this book, no boldfacing of vectors/matrices is shown to retain consistency with .m files.

The arithmetic operators + and – can be used to add or subtract matrices, vectors or scalars. Vectors denote one-dimensional arrays and matrices denote multidimensional arrays. For example,

>> x=[1,3,4]

>> y=[4,5,6]

>> x+y

ans=

5 8 10

In this example, the operator + adds the elements of the vectors x and y, element by element, assuming that the two vectors have the same dimension, in this case 1×31×3 size 12{1 times 3} {} or one row with three columns. An error occurs if one attempts to add vectors having different dimensions. The same applies for matrices.

To compute the dot product of two vectors (in other words, ixiyiixiyi size 12{ Sum cSub { size 8{i} } {x rSub { size 8{i} } y rSub { size 8{i} } } } {} ), use the multiplication operator ‘*’ as follows:

>> x*y'

ans =

43

Note the single quote after y denotes the transpose of a vector or a matrix.

To compute an element-by-element multiplication of two vectors (or two arrays), use the following operator:

>> x .* y

ans =

4 15 24

That is, x .* y means [1×4,3×5,4×6][1×4,3×5,4×6] size 12{ $1 times 4,3 times 5,4 times 6$ } {} = [41524][41524] size 12{ $matrix { 4 {} # "15" {} # "24"$ {} } } {}.

## Complex Numbers

LabVIEW MathScript supports complex numbers. The imaginary number is denoted with the symbol i or j, assuming that these symbols have not been used any other place in the program. It is critical to avoid such a symbol conflict for obtaining correct outcome. Enter the following and observe the outcomes:

>> z=3 + 4i % note the multiplication sign ‘*’ is not needed after 4

>> conj(z) % computes the conjugate of z

>> angle(z) % computes the phase of z

>> real(z) % computes the real part of z

>> imag(z) % computes the imaginary part of z

>> abs(z) % computes the magnitude of z

One can also define an imaginary number with any other user-specified variables. For example, try the following:

>> img=sqrt(-1)

>> z=3+4*img

>> exp(pi*img)

## Array Indexing

In .m files, all arrays (vectors) are indexed starting from 1 − in other words, x(1) denotes the first element of the array x. Note that the arrays are indexed using parentheses (.) and not square brackets [.], as done in C/C++. To create an array featuring the integers 1 through 6 as elements, enter:

>> x=[1,2,3,4,5,6]

Alternatively, use the notation ‘:’

>> x=1:6

This notation creates a vector starting from 1 to 6, in steps of 1. If a vector from 1 to 6 in steps of 2 is desired, then type:

>> x=1:2:6

ans =

1 3 5

Also, examine the following code:

>> ii=2:4:17

>> jj=20:-2:0

>> ii=2:(1/10):4

One can easily extract numbers in a vector. To concatenate an array, the example below shows how to use the operator ‘[ ]’:

>> x=[1:3 4 6 100:110]

To access a subset of this array, try the following:

>> x(3:7)

>> length(x) % gives the size of the array or vector

>> x(2:2:length(x))

## Allocating Memory

One can allocate memory for one-dimensional arrays (vectors) using the command zeros. The following command allocates memory for a 100-dimensional array:

>> y=zeros(100,1);

>> y(30)

ans =

0

One can allocate memory for two-dimensional arrays (matrices) in a similar fashion. The command

>> y=zeros(4,5)

defines a 4 by 5 matrix. Similar to the command zeros, the command ones can be used to define a vector containing all ones,

>> y=ones(1,5)

ans=

1 1 1 1 1

## Special Characters and Functions

Some common special characters used in .m files are listed below for later reference:

 Symbol Meaning pi π ( 3 . 14 . . . . . ) π ( 3 . 14 . . . . . ) size 12{π $$3 "." "14" "." "." "." "." "."$$ } {} ^ indicates power (for example, 3^2=9) NaN not-a-number, obtained when encountering undefined operations, such as 0/00/0 size 12{0/0} {} Inf Represents +∞+∞ size 12{+ infinity } {} ; indicates the end of a row in a matrix; also used to suppress printing on the screen (echo off) % comments − anything to the right of % is ignored by the .m file interpreter and is considered to be comments ‘ denotes transpose of a vector or a matrix; also used to define strings, for example, str1='DSP' … denotes continuation; three or more periods at the end of a line continue current function to next line

Some special functions are listed below for later reference:

 Function Meaning sqrt indicates square root, for example, sqrt(4)=2 abs absolute value ∣.∣∣.∣ size 12{ lline "." rline } {}, for example, abs(-3)=3 length length(x) gives the dimension of the array x sum finds sum of the elements of a vector find finds indices of nonzero

Here is an example of the function length,

>> x=1:10;

>> length(x)

ans =

10

The function find returns the indices of a vector that are non-zero. For example,

I = find(x>4) finds all the indices of x greater than 4. Thus, for the above example:

>> find(x> 4)

ans =

5 6 7 8 9 10

## Control Flow

.m files have the following control flow constructs:

• if statements

• switch statements

• for loops

• while loops

• break statements

The constructs if, for, switch and while need to terminate with an end statement. Examples are provided below:

if

>> x=-3;

if x>0

str='positive'

elseif x<0

str='negative'

elseif x== 0

str='zero'

else

str='error'

end

See the value of 'str' after executing the above code.

while

>> x=-10;

while x<0

x=x+1;

end

See the value of x after executing the above code.

for loop

>> x=0;

for j=1:10

x=x+j;

end

The above code computes the sum of all the numbers from 1 to 10.

break

With the break statement, one can exit early from a for or a while loop:

>> x=-10;

while x<0

x=x+2;

if x = = -2

break;

end

end

LabVIEW MathScript supports the relational and logical operators listed below.

Relational Operators

 Symbol Meaning <= less than equal < less than >= greater than equal > greater than == equal ~= not equal

Logical Operators

 Symbol Meaning & AND ∣ ∣ size 12{ \lline } {} OR ~ NOT

## Programming in the LabVIEW MathScript Window

The MathScript feature allows one to include .m files, which can be created using any text editor. To activate the LabVIEW MathScript interactive window, select Tools MathScript Window from the main menu. To open the LabVIEW MathScript text editor, click the Script tab of the LabVIEW MathScript Window (see Figure 1). After typing the .m file textual code, save it and click on the Run script button (green arrow) to run it.

For instance, to write a program to compute the average (mean) of a vector x, the program should use as its input the vector x and return the average value. To write this program, follow the steps outlined below.

Type the following in the empty script:

x=1:10

L=length(x);

sum=0;

for j=1:L

sum=sum+x(j);

end

y=sum/L % the average of x

From the Editor pull-down menu, go to File Save Script As and enter average.m for the file name. Then click on the Run script button to run the program. Figure 1 shows the LabVIEW MathScript interactive window after running the program.

## Sound Generation

Assuming the computer used has a sound card, one can use the function sound to play back speech or audio files through its speakers. That is, sound(y,FS) sends the signal in a vector y (with sample frequency FS) out to the speaker. Stereo sounds are played on platforms that support them, with y being an N-by-2 matrix.

Try the following code and listen to a 400 Hz tone:

>> t=0:1/8000:1;

>> x=cos(2*pi*400*t);

>> sound(x,8000);

Now generate a noise signal by typing:

>> noise=randn(1,8000); % generate 8000 samples of noise

>> sound(noise,8000);

The function randn generates Gaussian noise with zero mean and unit variance.

One can load or store data using the commands load and save. To save the vector x of the above code in the file data.mat, type:

>> save data x

Note that LabVIEW MathScript data files have the extension .mat. To retrieve the data saved, type:

>> load data

The vector x gets loaded in memory. To see memory contents, use the command whos,

>> whos

Variable Dimension Type x   1x8000 double array

The command whos gives a list of all the variables currently in memory, along with their dimensions. In the above example, x contains 8000 samples.

To clear up memory after loading a file, type clear all when done. This is important because if one does not clear all the variables, one could experience conflicts with other programs using the same variables.

## Reading Wave and Image Files

With LabVIEW MathScript, one can read data from different file types (such as .wav, .jpeg and .bmp) and load them in a vector.

To read an audio data file with .wav extension, use the following command:

>> [y Fs]=wavread(‘filename’)

This command reads a wave file specified by the string filename and returns the sampled data in y with the sampling rate of Fs (in hertz).

To read an image file, use the following command:

>> [y]=imread(‘filename’, ‘filetype’)

This command reads a grayscale or color image from the string filename, where filetype specifies the format of the file and returns the image data in the array y.

## Signal Display

Several tools are available in LabVIEW to display data in a graphical format. Throughout the book, signals in both the time and frequency domains are displayed using the following two graph tools.

Waveform Graph—Displays data acquired at a constant rate.

XY Graph—Displays data acquired at a non-constant rate, such as data acquired when a trigger occurs. A waveform graph can be created on a front panel by choosing Controls Express Waveform Graph. Figure 2 shows a waveform graph and the waveform graph elements which can be opened by right-clicking on the graph and selecting Visible Items from the shortcut menu.

Often a waveform graph is tied with the function Build Waveform(Function Programming Waveform Build Waveform) to calibrate the x scale (which is time scale for signals), as shown in Figure 3.

Create an XY graph from a front panel by choosing Controls Express XY Graph. Figure 4 shows an XY graph and its different elements.

An XY graph displays a signal at a non-constant rate, and one can tie together its X and Y vectors to display the signal via the Build XY Graph function. This function automatically appears on the block diagram when placing an XY graph on the front panel, as shown in Figure 5. Note that one can use the function Bundle (Functions Programming Cluster & Variant Bundle) instead of Build XY Graph.

## Hybrid Programming

As stated earlier, the LabVIEW MathScript feature can be used to perform hybrid programming, in other words, a combination of textual .m files and graphical objects. Normally, it is easier to carry out math operations via .m files while maintaining user interfacing, interactivity and analysis in the more intuitive graphical environment of LabVIEW. Textual .m file codes can be typed in or copied and pasted into LabVIEW MathScript nodes.

### Sum and Average VI Example Using Hybrid Programming

Sum and Average VI Example Using Hybrid Programming

Choose Functions Programming Structures MathScript to create a LabVIEW MathScript node (see Figure 6). Change the size of the window by dragging the mouse.

Now build the same program average using a LabVIEW MathScript node. The inputs to this program consist of x and y. To add these inputs, right-click on the border of the LabVIEW MathScript node and click on the Add Input option (see Figure 7).

After adding these inputs, create controls to change the inputs interactively via the front panel. By right-clicking on the border, add outputs in a similar manner. An important issue to consider is the selection of output data type. The outputs of the Sum and Average VI are scalar quantities. Choose data types by right-clicking on an output and selecting the Choose Data Type option (see Figure 8).

Finally, add numeric indicators in a similar fashion as indicated earlier. Figure 9 shows the completed block diagram and front panel.

### Building a Signal Generation System Using Hybrid Programming

In this section, let us see how to generate and display aperiodic continuous-time signals or pulses in the time domain. One can represent such signals with a function of time. For simulation purposes, a representation of time tt size 12{t} {}is needed. Note that the time scale is continuous while computer programs operate in a discrete fashion. This simulation can be achieved by considering a very small time interval. For example, if a 1-second duration signal in millisecond increments (time interval of 0.001 second) is considered, then one sample every 1 millisecond and a total of 1000 samples are generated for the entire signal. This continuous-time signal approximation is discussed further in later chapters. It is important to note that there is a finite number of samples for a continuous-time signal, and, to differentiate this signal from a discrete-time signal, one must assign a much higher number of samples per second (very small time interval).

Figure 10 shows two continuous-time signals x1(t)x1(t) size 12{x1 $$t$$ } {} and x2(t)x2(t) size 12{x2 $$t$$ } {}with a duration of 3 seconds. By setting the time interval dt to 0.001 second, there is a total of 3000 samples at t=0,0.001,0.002,0.003,.......,2.999t=0,0.001,0.002,0.003,.......,2.999 size 12{t=0,0 "." "001",0 "." "002",0 "." "003", "." "." "." "." "." "." "." ,2 "." "999"} {} seconds.

The signal x1(t)x1(t) size 12{x1 $$t$$ } {} can be represented mathematically as follows:

x1(t)={00t<111t<202t<3x1(t)={00t<111t<202t<3 size 12{x1 $$t$$ = left lbrace matrix { 0 {} # 0 <= t<1 {} ## 1 {} # 1 <= t<2 {} ## 0 {} # 2 <= t<3{} } right none } {}
(1)

To simulate this signal, use the LabVIEW MathScript functions ones and zeros. The signal value is zero during the first second, which means the first 1000 samples are zero. This portion of the signal is simulated with the function zeros(1,1000). In the next second (next 1000 samples), the signal value is 2, and this portion is simulated by the function 2*ones(1,1000). Finally, the third portion of the signal is simulated by the function zeros(1,1000). In other words, the entire duration of the signal is simulated by the following .m file function:

x1=[ zeros(1,1/dt) 2*ones(1,1/dt) zeros(1,1/dt)]

The signal x2(t)x2(t) size 12{x2 $$t$$ } {} can be represented mathematically as follows:

x2(t)={2t0t<12t+41t<202t<3x2(t)={2t0t<12t+41t<202t<3 size 12{x2 $$t$$ = left lbrace matrix { 2t {} # 0 <= t<1 {} ## - 2t+4 {} # 1 <= t<2 {} ## 0 {} # 2 <= t<3{} } right none } {}
(2)

Use a linearly increasing or decreasing vector to represent the linear portions. The time vectors for the three portions or segments of the signal are 0:dt:1-dt, 1:dt:2-dt and 2:dt:3-dt. The first segment is a linear function corresponding to a time vector with a slope of 2; the second segment is a linear function corresponding to a time vector with a slope of -2 and an offset of 4; and the third segment is simply a constant vector of zeros. In other words, simulate the entire duration of the signal for any value of dt by the following .m file function:

x2=[2*(0:dt:(1-dt)) -2*(1:dt:(2-dt))+4 zeros(1,1/dt)].

Figure 11 and Figure 12 show the block diagram and front panel of the above signal generation system, respectively. Display the signals using a Waveform Graph(Controls Express Waveform Graph) and a Build Waveform function (Function Programming Waveform Build Waveform). Note that the default data type in MathScript is double precision scalar. So whenever an output possesses any other data type, one needs to right-click on the output and select the Choose Data Type option. In this example, x1 and x2 are double precision one-dimensional arrays that are specified accordingly.

### Building a Periodic Signal Generation System Using Hybrid Programming

In this section, build a simple periodic signal generation system in hybrid mode to set the stage for the chapters that follow. This system involves generating a periodic signal in textual mode and displaying it in graphical mode. Modify the shape of the signal (sine, square, triangle or sawtooth) as well as its frequency and amplitude by using appropriate front panel controls. The block diagram and front panel of this system using a LabVIEW MathScript node are shown in Figure 13 and Figure 14, respectively. The front panel includes the following three controls:

Waveform type – Select the shape of the input waveform as either sine, square, triangular or sawtooth waves.

Amplitude – Control the amplitude of the input waveform.

Frequency – Control the frequency of the input waveform.

To build the block diagram, first write a .m file code to generate four types of waveforms using the .m file functions sin, square and sawtooth. To change the amplitude and frequency of the waveforms, use two controls named Amplitude (A) and Frequency (f). Waveform Type (w) is another input controlled by the Enum Control for selecting the waveform type. With this control, one can select from multiple inputs. Create an Enum Control from the front panel by invoking Controls Modern Ring & Enum Enum. Right-click on the Enum Control to select properties and the edit item tab to choose different items as shown in Figure 15. After inserting each item, the digital display shows the corresponding number value for that item, which is the output of the Enum Control.

Finally, display the waveforms with a Waveform Graph(Controls Express Waveform Graph) and a Build Waveform function (Function Programming Waveform Build Waveform).

## Lab Exercises

### Exercise 1

Write a .m file code to add all the numbers corresponding to the even indices of an array. For instance, if the array x is specified as x = [1, 3, 5, 10], then 13 (= 3+10) should be returned. Use the program to find the sum of all even integers from 1 to 1000. Run your code using the LabVIEW MathScript interactive window. Also, redo the code where x is the input vector and y is the sum of all the numbers corresponding to the even indices of x.

#### Solution

Insert Solution Text Here

### Exercise 2

2. Explain what the following .m file does:

L=length(x);

for j=1:L

if x(j) < 0

x(j)=-x(j);

end

end

Rewrite this program without using a for loop.

#### Solution

Insert Solution Text Here

### Exercise 3

3. Write a .m file code that implements the following hard-limiting function:

x(t)={0.2t0.20.2t<0.2x(t)={0.2t0.20.2t<0.2 size 12{x $$t$$ = left lbrace matrix { 0 "." 2 {} # t >= 0 "." 2 {} ## - 0 "." 2 {} # t<0 "." 2{} } right none } {}
(3)

For tt size 12{t} {}, use 1000 random numbers generated via the function rand.

#### Solution

Insert Solution Text Here

### Exercise 4

4. Build a hybrid VI to generate two sinusoid signals with the frequencies f1 Hz and f2 Hz and the amplitudes A1 and A2, based on a sampling frequency of 8000 Hz with the number of samples being 256. Set the frequency ranges from 100 to 400 Hz and set the amplitude ranges from 20 to 200. Generate a third signal with the frequency f3 = (mod (lcm (f1, f2), 400) + 100) Hz, where mod and lcm denote the modulus and least common multiple operation, respectively, and the amplitude A3 is the sum of the amplitudes A1 and A2. Use the same sampling frequency and number of samples as specified for the first two signals. Display all the signals using the legend on the same waveform graph and label them accordingly.

#### Solution

Insert Solution Text Here

## Content actions

PDF | EPUB (?)

### What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks