Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjlnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
So You Think You Can
MathScript HANS-PETTER HALVORSEN, 2011.09.07
Part I: Introduction to MathScript
ii
Preface
Purpose with this Lab
In this lab you will learn how to use a tool like MathScript (which has a similar syntax as MATLAB) to
solve control and simulation problems.
For additional information and resources:
http://home.hit.no/~hansha/?lab=mathscript
MathScript
MathScript is a high-level, text- based programming language. MathScript includes more than 800
built-in functions and the syntax is similar to MATLAB. You may also create custom-made m-file like
you do in MATLAB.
MathScript is an add-on module to LabVIEW but you dont need to know LabVIEW programming in
order to use MathScript.
http://home.hit.no/~hansha/?lab=mathscript
iii
What is LabVIEW?
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and
development environment for a visual programming language from National Instruments. The
graphical language is named G.
What is MATLAB?
MATLAB is a tool for technical computing, computation and visualization in an integrated
environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix
manipulation and problem solving related to Linear Algebra.
MATLAB offers lots of additional Toolboxes for different areas such as Control Design, Image
Processing, Digital Signal Processing, etc.
What is MathScript?
MathScript is a high-level, text- based programming language. MathScript includes more than 800
built-in functions and the syntax is similar to MATLAB. You may also create custom-made m-file like
you do in MATLAB.
MathScript is an add-on module to LabVIEW but you dont need to know LabVIEW programming in
order to use MathScript. If you want to integrate MathScript functions (built-in or custom-made
m-files) as part of a LabVIEW application and combine graphical and textual programming, you can
work with the MathScript Node.
In addition to the MathScript built-in functions, different add-on modules and toolkits installs
additional functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital
Filter Design Toolkit install lots of additional functions.
You can more information about MathScript here: http://www.ni.com/labview/mathscript.htm
How do you start using MathScript?
You need to install LabVIEW and the LabVIEW MathScript RT Module. When necessary software is
installed, start MathScript by open LabVIEW:
http://home.hit.no/~hansha/documents/software/LabVIEW.htmhttp://home.hit.no/~hansha/documents/software/MATLAB.htmhttp://home.hit.no/~hansha/documents/software/LabVIEW%20MathScript%20RT%20Module.htmhttp://home.hit.no/~hansha/documents/software/LabVIEW%20Control%20Design%20and%20Simulation%20Module.htmhttp://www.ni.com/labview/mathscript.htmhttp://home.hit.no/~hansha/documents/software/LabVIEW.htmhttp://home.hit.no/~hansha/documents/software/LabVIEW%20MathScript%20RT%20Module.htm
iv
In the Getting Started window, select Tools -> MathScript Window...:
v
Table of Contents
Preface ......................................................................................................................................................ii
Purpose with this Lab ...........................................................................................................................ii
MathScript............................................................................................................................................ii
Table of Contents ..................................................................................................................................... v
1 Introduction to MathScript ............................................................................................................. 6
1.1 Additional Resources ............................................................................................................... 6
1.2 Getting Started ........................................................................................................................ 6
1.3 Basic Operations ...................................................................................................................... 9
1.4 Matrices and Vectors............................................................................................................. 12
1.5 Solving Linear Equations ........................................................................................................ 15
2 Plotting.......................................................................................................................................... 17
2.1 Sub-plots ................................................................................................................................ 21
3 Functions ...................................................................................................................................... 23
3.1 Calling functions In MathScript ............................................................................................. 23
3.2 User-Defined Functions in MathScript .................................................................................. 23
3.3 Scripts .................................................................................................................................... 25
4 Flow Control.................................................................................................................................. 27
5 Additional Tasks ............................................................................................................................ 29
Appendix A MathScript Functions ...................................................................................................... 33
Basic Functions .................................................................................................................................. 33
Basic Plotting Functions .................................................................................................................... 33
Linear Algebra ................................................................................................................................... 34
6
1 Introduction to
MathScript
1.1 Additional Resources
MathScript is a high-level, text- based programming language. MathScript includes more than 800
built-in functions and the syntax is similar to MATLAB. You may also create custom-made m-file like
you do in MATLAB.
MathScript is an add-on module to LabVIEW but you dont need to know LabVIEW programming in
order to use MathScript.
You need to install the LabVIEW MathScript RT Module in addition to LabVIEW before you start
this Lab Work.
Background information for this lab is described in detailed in the LabVIEW MathScript
Tutorial. The Tutorial consists of pdf documents, videos, example code, additional resources and
links.
You should also read MathScript Basics by Richard C Dorf and Robert H. Bishop -
Modern Control Systems.
The document Control Theory with MathScript Examples gives an overview of the basic
cybernetics theory needed for this Lab Work with lots of MathScript Examples.
Link to these documents are located here: http://home.hit.no/~hansha/?lab=mathscript
1.2 Getting Started
How do you start using MathScript? You need to install LabVIEW and the LabVIEW MathScript RT
Module. When necessary software is installed, start MathScript by open LabVIEW:
http://home.hit.no/~hansha/documents/software/LabVIEW%20MathScript%20RT%20Module.htmhttp://home.hit.no/~hansha/?tutorial=mathscripthttp://home.hit.no/~hansha/documents/labview/training/LabVIEW%20MathScript/Background/MathScript%20Basics.pdfhttp://home.hit.no/~hansha/documents/control/Documents/Lecture%20Notes/Control%20Theory%20with%20MathScript%20Examples.pdfhttp://home.hit.no/~hansha/?lab=mathscript
7 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
In the Getting Started window, select Tools -> MathScript Window...:
The LabVIEW MathScript Window is an interactive interface in which you can enter .m file script
commands and see immediate results, variables and commands history. The window includes a
command-line interface where you can enter commands one-by-one for quick calculations, script
debugging or learning. Alternatively, you can enter and execute groups of commands through a script
editor window.
As you work, a variable display updates to show the graphical / textual results and a history window
tracks your commands. The history view facilitates algorithm development by allowing you to use the
clipboard to reuse your previously executed commands.
8 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
You can use the LabVIEW MathScript Window to enter commands one at time. You also can enter
batch scripts in a simple text editor window, loaded from a text file, or imported from a separate text
editor. The LabVIEW MathScript Window provides immediate feedback in a variety of forms, such
as graphs and text.
9 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
1.3 Basic Operations
Below we see MathScript and the Command window:
You use the Command window to enter commands to MathScript. The results are shown in the
Output Window. If we want to enter a collection of different commands that belong together, we
use the Script window.
Variables:
Variables are defined with the assignment operator, =. MathScript is dynamically typed, meaning
that variables can be assigned without declaring their type, and that their type can change. Values
can come from constants, from computation involving values of other variables, or from the output
of a function.
Note! MathScript is case sensitive! The variables x and X are not the same.
Example:
Type the following in the Command window:
>>y=16;
>>z=3;
>>y+z
Note! When you use a semicolon, no output will be displayed. Try the code above with and without
semicolon.
Other basic operations are:
10 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
>>16-3
>>16/3
>>16*3
Try them.
[End of Example]
Example:
Given the following simple function:
( )
We want to find ( )
In order to do that, we type the following in the Command Window:
First we need to define x:
x=2
Then we can define the function:
y = 3*x + 2
Then MathScript respond with the following answer:
y =
8
[End of Example]
Task 1: Math function
Given the following function:
( )
Find ( ) and ( )
[End of Task]
Task 2: Math function
Create the following mathematical expression in MathScript:
11 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
( )
is a function of and , i.e. ( ). Use MathScript to find ( ).
Tip! Use the following built-in functionality:
x^2
sqrt(x)
( ) log(x)
exp(x)
[End of Task]
12 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
1.4 Matrices and Vectors
Matrices and vectors (Linear Algebra) are the basic elements in MathScript and also the basic
elements in control design theory. So it is important you know how to handle vectors and matrices in
MathScript.
The Tutorial LabVIEW MathScript describes the basic syntax of Linear Algebra in
MathScript.
Vectors:
Given the following vector:
[ ]
This can be implemented in MathScript like this:
x =[1, 2, 3]
The colon notation is very useful for creating vectors:
Example:
x=1:5
This gives:
x =
1 2 3 4 5
x=1:0.5:3
This gives:
http://home.hit.no/~hansha/documents/labview/training/LabVIEW%20MathScript/LabVIEW%20MathScript.pdf
13 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
x =
1 1.5 2 2.5 3
[End of Example]
Matrices:
A general matrix may be written like this:
[
]
Basically, a matrix is a 2 dimensional array with rows and columns.
Example:
Given the following matrix:
*
+
MathScript Code:
A=[1, 2; 3, 4]
Note! , (or just an empty space) is used to separate elements in a row, while ; is used to define a
new row.
[End of Example]
How to get a subset of a matrix:
Example:
We want to find the value in the second row and the second column of matrix A:
A(2,2)
This gives:
ans =
4
We want to find the second row of matrix A:
A(2,:)
This gives:
ans =
14 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
3 4
We want to find the second column of matrix A:
A(:,2)
This gives:
ans = 2
4
[End of Example]
Task 3: Vectors and Matrices
Type the following vector in MathScript in the Command window:
[ ]
Type the following matrix in MathScript in the Command window:
*
+
Type the following matrix in MathScript in the Command window:
[
]
Use Use MathScript to find the value in the second row and the third column of matrix C.
Use MathScript to find the second row of matrix C.
Use MathScript to find the third column of matrix C.
[End of Task]
Task 4: Linear Algebra
(You may want to skip this task if you havent learned about Linear Algebra yet)
Given the matrix A, B and C:
*
+ *
+ *
+
Solve the following basic matrix operations using MathScript:
15 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
( ) ( )
( ) ( )
( )
( )
where eig = Eigenvalues, diag = Diagonal, det = Determinant
[End of Task]
Task 5: Matrices
(You may want to skip this task if you havent learned about Linear Algebra yet)
Use MathScript to prove the following:
( ) ( )
( )
( )
( ) ( ) ( )
( ) ( )
where is the unit matrix
[End of Task]
1.5 Solving Linear Equations
Task 6: Equations
(You may want to skip this task if you havent learned about Linear Algebra yet)
Given the equations:
Set the equations on the following form:
16 Introduction to MathScript
MathScript - Part I: Introduction to MathScript
Find A and b.
Solve the equations, i.e., find , using MathScript.
[End of Task]
17
2 Plotting
MathScript has lots functions used for plotting:
Function Description Example
plot Generates a plot. plot(y) plots the columns of y against the indexes of the columns.
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
figure Create a new figure window >>figure >>figure(1)
subplot Create subplots in a Figure. subplot(m,n,p) or subplot(mnp), breaks the Figure window into an m-by-n matrix of small axes, selects the p-th axes for the current plot. The axes are counted along the top row of the Figure window, then the second row, etc.
>>subplot(2,2,1)
grid Creates grid lines in a plot. grid on adds major grid lines to the current plot. grid off removes major and minor grid lines from the current plot.
>>grid
>>grid on
>>grid off
axis Control axis scaling and appearance. axis(*xmin xmax ymin ymax+) sets the limits for the x- and y-axis of the current axes.
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on title Add title to current plot
title('string')
>>title('this is a title')
xlabel Add xlabel to current plot xlabel('string')
>> xlabel('time')
ylabel Add ylabel to current plot ylabel('string')
>> ylabel('temperature')
legend Creates a legend in the corner (or at a specified position) of the plot
>> legend('temperature')
hold Freezes the current plot, so that additional plots can be overlaid >>hold on >>hold off
Below we see some examples of how to use the different plot functions:
18 Plotting
MathScript - Part I: Introduction to MathScript
For line colors and line-styles we have the following properties we can use for the plot function:
Line Styles:
Marker specifiers:
19 Plotting
MathScript - Part I: Introduction to MathScript
Colors:
We will use this in some tasks below.
20 Plotting
MathScript - Part I: Introduction to MathScript
Task 7: Plotting
In the Command window in MathScript window input the time from t=0 seconds to t=10 seconds in
increments of 0.1 seconds as follows:
>>t=[0:0.1:10];
Then, compute the output y as follows:
>>y=cos(t);
Use the Plot command:
>>plot(t,y)
[End of Task]
Task 8: Plotting
Plot ( ) and ( ) for in the same plot.
Tip! You can use the hold on command in addition to the plot command or you can use the plot
command like this:
Plot(x1,y1, x2,y2, )
Make sure to add labels and a legend, and use different line styles and colors for the plots.
Note! We cannot use Greek letters in MathScript, but use, e.g., theta, x or another name for your
variable.
[End of Task]
Task 9: Plot of dynamic system
Given the following differential equation:
where
,where is the time constant
The solution for the differential equation is:
( )
Set and the initial condition ( )
21 Plotting
MathScript - Part I: Introduction to MathScript
Plot the solution ( ) in the time interval
Add Grid, and proper Title and Axis Labels to the plot.
[End of Task]
2.1 Sub-plots
The subplot command enables you to display multiple plots in the same window or print them on the
same piece of paper. Typing subplot(m,n,p) partitions the figure window into an m-by-n matrix of
small subplots and selects the pth subplot for the current plot. The plots are numbered along the first
row of the figure window, then the second row, and so on.
The syntax is as follows:
subplot(m,n,p)
Example:
x=1:5;
subplot(2,1,1)
y=3*x+2;
plot(x,y)
subplot(2,1,2)
z=-2*x+2;
plot(x,z)
This gives the following plot:
22 Plotting
MathScript - Part I: Introduction to MathScript
[End of Example]
Task 10: Sub-plots
Plot sin(x) and cos(x) in 2 different subplots.
Add Titles and Labels.
[End of Task]
23
3 Functions
3.1 Calling functions In MathScript
MathScript includes more than 800 built-in functions that you can use, e.g., in a previous task you
used the plot function.
Task 11: Statistics
Given the vector:
>>x=[1 2 5 6 8 9 3]
Find the mean value of the vector x.
Find the minimum value of the vector x.
Find the maximum value of the vector x.
[End of Task]
3.2 User-Defined Functions in MathScript
So far we have used the Command Window in MathScript, but now we will start using the Script
Window in MathScript.
MathScript includes more than 800 built-in functions that you can use but sometimes you need to
create your own functions.
To define your own function in MathScript, use the following syntax:
function outputs = function_name(inputs)
% documentation
Example:
We will create a simple function that finds the sum of two numbers:
24 Functions
MathScript - Part I: Introduction to MathScript
function total = add(x,y)
% this function add 2 numbers
total = x+y;
Note! You need to save this as a file with extension .m with the same name as the function, i.e.,
add.m In this example are x and y inputs to the function, while total is an output from the function.
You may use the function like this:
%Example 1:
add(2,3)
%Example 2:
a=4;
b=6;
add(a,b);
%Example 3:
answer = add(a,b)
[End of Example]
Here is the procedure for creating a user-defined function in MathScript:
Task 12: User-defined function
Create a function calc_average that finds the average of two numbers.
25 Functions
MathScript - Part I: Introduction to MathScript
Test the function afterwards as follows:
>>x=2;
>>y=4;
>>z=calc_average(x,y)
[End of Task]
3.3 Scripts
A script is a sequence of MathScript commands that you want to perform to accomplish a task. When
you have created the script you may save it as a m-file for later use.
Task 13: Script
Create a new Script where you use the function you created in the previous task. Call it several times
with different inputs.
[End of Task]
Task 14: Conversion
It is quite easy to convert from radians to degrees or from degrees to radians. We have that:
[ ] [ ]
This gives:
26 Functions
MathScript - Part I: Introduction to MathScript
[ ] [ ] (
)
[ ] [ ] (
)
Create two functions that convert from radians to degrees (r2d(x)) and from degrees to radians
(d2r(x)) respectively.
Test the functions to make sure that they work as expected, e.g.:
>> r2d(2*pi)
ans =
360
>> d2r(180)
ans =
3.1416
[End of Task]
27
4 Flow Control
You may use different loops in MathScript
For loop
While loop
If you want to control the flow in your program, you may want to use one of the following:
If-else statement
Switch and case statement
Task 15: For Loop
Extend your calc_average function from a previous task so it can calculate the average of a vector
with random elements. Use a For loop to iterate through the values in the vector and find sum in
each iteration, e.g.:
mysum = mysum + x(i);
Test the function in the Command window
[End of Task]
Task 16: If-else
Depending on a variable a, different functions should be executed and plotted.
( )
( )
( )
Create a script that plot based on the value of the input .
[End of Task]
Task 17: Fibonacci Numbers
28 Flow Control
MathScript - Part I: Introduction to MathScript
In mathematics, Fibonacci numbers are the numbers in the following sequence:
0, 1, 1, 2 , 3, 5, 8, 13, 21, 34, 55, 89, 144,
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum
of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
In mathematical terms, the sequence of Fibonacci numbers is defined by the recurrence relation:
with seed values:
Write a function in MathScript that calculates the N first Fibonacci numbers, e.g.,
>> N=10;
>> fibonacci(N)
ans =
0
1
1
2
3
5
8
13
21
34
Use a For loop to solve the problem.
Fibonacci numbers are used in the analysis of financial markets, in strategies such as Fibonacci
retracement, and are used in computer algorithms such as the Fibonacci search technique and the
Fibonacci heap data structure. They also appear in biological settings, such as branching in trees,
arrangement of leaves on a stem, the fruitlets of a pineapple, the flowering of artichoke, an uncurling
fern and the arrangement of a pine cone.
[End of Task]
29
5 Additional Tasks
Here are some additional tasks:
Task 18: If-else
Given the second order algebraic equation:
The solution (roots) is as follows:
{
where - there is no solution, - any complex number is a solution
Create a function that finds the solution for based on different input values for a, b and c, e.g.,
function x = solveeq(a,b,c)
Use if-else statements to solve the problems
Test the function from the Command window to make sure it works as expected, e.g.,
>> a=0, b=2, c=1
>> solveeq(a,b,c)
Compare the result with the results you get from the built-in roots function.
[End of Task]
Task 19: Basic Math function
Create a function that calculates the following mathematical expression:
( )
30 Additional Tasks
MathScript - Part I: Introduction to MathScript
We can test the function like this:
Testing the function gives (in this example the name of our function is calcexpression):
>> x=2; y=2;
>> calcexpression(x,y)
ans =
16.8284
[End of Task]
Task 20: User-defined function
Create a function that uses Pythagoras to calculate the hypotenuse of a right-angled triangle, e.g.:
function h = pyt(a,b)
% ..
h =
Pythagoras theorem is as follows:
Note! The function should handle that a and b could be vectors.
[End of Task]
Task 21: Cylinder surface area
Create a function that finds the surface area of a cylinder based on the height (h) and the radius (r) of
the cylinder.
31 Additional Tasks
MathScript - Part I: Introduction to MathScript
[End of Task]
Task 22: Create advanced expressions in MathScript
Create the following expression in MathScript:
( ) ( ) ( )
( )( )
Given
Find ( )
(The answer should be ( ) )
Tip! You should split the expressions into different parts, such as:
poly =
num =
den =.
f =
This makes the expression simpler to read and understand, and you minimize the risk of making an
error while typing the expression in MathScript.
[End of Task]
Task 23: Solving Equations
Find the solution(s) for the given equations:
32 Additional Tasks
MathScript - Part I: Introduction to MathScript
[End of Task]
Task 24: Script
Given the famous equation from Albert Einstein:
The sun radiates of energy per day.
Calculate how much of the mass on the sun is used to create this energy per day.
How many years will it take to convert all the mass of the sun completely? Do we need to worry if
the sun will be used up in our generation or the next?
The mass of the sun is
[End of Task]
33
Appendix A MathScript
Functions
Basic Functions
Here are some descriptions for the most used basic MathScript functions.
Function Description Example
help MathScript displays the help information available >>help
help
Display help about a specific function >>help plot
who, whos who lists in alphabetical order all variables in the currently active workspace.
>>who
>>whos
clear Clear variables and functions from memory. >>clear >>clear x
size Size of arrays, matrices >>x=[1 2 ; 3 4]; >>size(A)
length Length of a vector >>x=[1:1:10]; >>length(x)
format Set output format
disp Display text or array >>A=[1 2;3 4]; >>disp(A)
plot This function is used to create a plot >>x=[1:1:10]; >>plot(x)
>>y=sin(x);
>>plot(x,y)
clc Clear the Command window >>cls
rand Creates a random number, vector or matrix >>rand >>rand(2,1)
max Find the largest number in a vector >>x=[1:1:10] >>max(x)
min Find the smallest number in a vector >>x=[1:1:10] >>min(x)
mean Average or mean value >>x=[1:1:10] >>mean(x)
std Standard deviation >>x=[1:1:10] >>std(x)
Basic Plotting Functions
Function Description Example
plot Generates a plot. plot(y) plots the columns of y against the indexes of the columns.
>X = [0:0.01:1];
>Y = X.*X;
>plot(X, Y)
figure Create a new figure window >>figure >>figure(1)
subplot Create subplots in a Figure. subplot(m,n,p) or subplot(mnp), breaks the Figure window into an m-by-n matrix of small axes, selects the p-th axes for the current plot. The axes are counted along the top row of the Figure window, then the second row,
>>subplot(2,2,1)
34 Appendix A MathScript Functions
MathScript - Part I: Introduction to MathScript
etc.
grid Creates grid lines in a plot. grid on adds major grid lines to the current plot. grid off removes major and minor grid lines from the current plot.
>>grid
>>grid on
>>grid off
axis Control axis scaling and appearance. axis(*xmin xmax ymin ymax+) sets the limits for the x- and y-axis of the current axes.
>>axis([xmin xmax ymin ymax])
>>axis off
>>axis on title Add title to current plot
title('string')
>>title('this is a title')
xlabel Add xlabel to current plot xlabel('string')
>> xlabel('time')
ylabel Add ylabel to current plot ylabel('string')
>> ylabel('temperature')
legend Creates a legend in the corner (or at a specified position) of the plot
>> legend('temperature')
hold Freezes the current plot, so that additional plots can be overlaid >>hold on >>hold off
For more information about the plots function, type help plots.
Linear Algebra
Here are some useful functions for Linear Algebra in MATLAB:
Function Description Example
rank Find the rank of a matrix. Provides an estimate of the number of linearly independent rows or columns of a matrix A.
>>A=[1 2; 3 4]
>>rank(A)
det Find the determinant of a square matrix >>A=[1 2; 3 4] >>det(A)
inv Find the inverse of a square matrix >>A=[1 2; 3 4] >>inv(A)
eig Find the eigenvalues of a square matrix >>A=[1 2; 3 4] >>eig(A)
ones Creates an array or matrix with only ones >>ones(2) >>ones(2,1)
eye Creates an identity matrix >>eye(2)
diag Find the diagonal elements in a matrix >>A=[1 2; 3 4] >>diag(A)
Type help matfun (Matrix functions - numerical linear algebra) in the Command Window for more
information, or type help elmat (Elementary matrices and matrix manipulation).
You may also type help for help about a specific function.
Telemark University College
Faculty of Technology
Kjlnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: [email protected]
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/mailto:[email protected]://home.hit.no/~hansha/