Using Mathematics Language
Mathematics Language, along with most of its built-in functions, was designed to be compatible with m-file script syntax.
Statements
An equation block consists of one or more statements. Statements are separated by line breaks, commas, or semicolons. The following two equation blocks are equivalent:
X = 2
Y = 3
and
X = 2, Y = 3
If you end a statement with a semicolon, it does not generate output in the command window.
Complicated statements can span multiple lines and use control structures like while loops, for loops, and if statements.
The following statement types are supported by Mathematics Language equations: assignment, comment, label, goto, if, for, while, function, or return. The format of each statement type is described below.
Assignments
An assignment statement assigns a value to a variable. The syntax of an assignment statement is as follows:
Variable_Name = Expression
For example,
X = 3.6;
Y = sin(3*PI);
Z = [1 2 3];
are all assignments.
A variable name must start with a letter, and can contain alphanumeric characters and underscore characters. An expression can contain numerical operations involving numbers, other variables, and function calls.
Vectors and matrices can be defined inline, as the following example illustrates:
x = [1 2 3] % a row vector
y = [1;2;3] % a column vector
z = [1 2 3; 4 5 6] % a 2x3 matrix
Comments
A comment starts with a percent character (%) and continues for the rest of that line. The following are examples of comments:
X = R * cos( theta ) % here is one comment
% Here is another comment
In the example above, the assignment statement is executed, while both comments are ignored.
if statement
The if statement is a control structure that allows one set of statements to execute if a condition is met, and optionally, another set of statements to execute if the condition is not met. Valid syntax for the if statement is:
if _expression_
one_or_more_statements
elseif
one_or_more_statements
else
one_or_more_statements
end
if _expression_
one_or_more_statements
end
if _expression,_ _statement,_ end
If expression evaluates to a nonzero value, the following statement block is executed, otherwise that statement block is skipped. If an else block is specified and expression evaluates to zero (false), the else block is executed. Expression is generally a Boolean expression.
Example:
x = 3
y = 2
if x == y % Note that double equals are used for comparison
x = x + 1
y = y - 2
else
x = 0
end
for statement
The for loop statement is a control structure that allows a set of statements to repeatedly execute according to the value of the loop variable. The syntax is as follows:
A loop variable named variable-name is initialized to the first column of <value>. The statement block following the for loop definition is executed, and the loop variable moves on to the second column of <values>, and so on. The statement block repeatedly executes until there are no more columns in <values>. The following example clarifies this:
x = 0, y = 0
for i = 1 : 5 % is [1 2 3 4 5]
x = x + 10
y = y + 100
end
After execution completes in the above example, i is equal to 5, x is equal to 50, and y is equal to 500.
while statement
The while loop statement is a control structure that executes a set of statements repeatedly based on a condition. The syntax is as follows:
As long as expression evaluates to a nonzero number, the statements execute. Once the last statement in one-or-more-statements is reached, expression is once again evaluated. When expression evaluates to zero (false), execution continues after end.
function statement
The function statement is used to define functions or procedures. A function takes zero or more parameters as input and returns exactly one value as output. All variables used within a function are local; that is, you cannot use variables defined in a function in another function or in the main equation block. However, you can use variables defined in the equation block in the function. The syntax of the function statement is as follows:
function = functionName( )
end % Note: this end is optional
If the function takes no parameters, the parentheses must still be present after function-name . If the function returns a value, you should set the values in the <resultlist> block.
<paramlist> and <resultlist> are lists of variable names separated by commas. If the last variable in <paramlist> is varargin, then the function can take in an unspecified number of arguments, and the remaining arguments are placed into the varargin cell array which can be accessed from within the function. Similarly, if the last variable in <resultlist> is varargout, then the function can return an unspecified number of return values which are set in the function by assigning to the varargout cell array.
Inside a function definition, you may use the variables named nargin and nargout which hold the number of arguments passed in to the function and the number of return values requested by the caller, respectively. These may be used for error checking or other purposes.
The following example is a function used to calculate the inductor value necessary to produce a resonance at a given resonant frequency and capacitor value:
function ind = ResL(C, F)
% L is in nH, C is in pF, F is in MHz
FHz = 1e6 * F
CFarads = 1e-12 * C
Omega = 2 * pi * FHz
LHenries = 1 / (Omega^2 * CFarads)
ind = LHenries * 1e9 % the return value
end
The function defined above may be called as follows:
L = ResL(50, 25.8) % get me the L value in nH for 50 pF and 25.8 MHz
You may return multiple values by listing them in the result expression, as in
function [Ind, Q] = ResL( C, F, R)
Ind = 1
Q = 2
end
this is used as [MyInd, MyQ] = Resl(a,b,c)
The following example illustrates a function that takes in a variable number of arguments and returns a variable number of results.
function varargout = f(varargin)
SumOfArgs = 0;
for i = 1 : nargin
SumOfArgs = SumOfArgs + varargin{i}
end
varargout{1} = SumOfArgs
if nargout > 1
varargout{2} = 2 * SumOfArgs
end
end
Suppose we call this function as follows:
[a, b, c] = f(1, 2, 3, 4)
a would be set to 10 (the sum of the input arguments), b would be set to 20, and c would be blank since it was not assigned to in the function.
Operators
Operators and their descriptions are listed in the table below. Examples for each operator are also listed.
| Operator |
Description |
Example |
| + |
Addition |
a + b |
| - |
Subtraction |
a - b |
| * |
Matrix Multiplication |
a * b |
| .* |
Element-by-Element Matrix Multiplication |
a .* b |
| / |
Matrix Right-Division |
a / b |
| ./ |
Element-by-Element Division |
a ./ b |
| \ |
Matrix Left-Division |
a \ b |
| .\ |
Element-by-Element Left-Division |
a .\ b |
| ^ |
Matrix Exponentiation |
a ^ 2 (means a-squared) |
| .^ |
Element-by-Element Exponentiation |
a .^ b |
| ' |
Matrix conjugate-transpose (hermitian) |
a' |
| .' |
Matrix transpose (no conjugation) |
a.' |
| & |
Element-wise Boolean And |
a & b |
| && |
Boolean And |
a && b |
| | |
Element-wise Boolean Or |
a | b |
| || |
Boolean Or |
a || b |
| ~ |
Boolean Not |
~a |
| = |
Assignment Operator |
a = 2 |
| == |
Boolean Comparison |
a == b |
| > |
Boolean Greater Than |
a > b |
| >= |
Boolean Greater Than or Equal |
a >= b |
| < |
Boolean Less Than |
a < b |
| <= |
Boolean Less Than or Equal |
a <= b |
| ~= |
Boolean Not Equal |
a ~= b |
Vectors, Matrices, and Multidimensional Arrays
Mathematics Language supports vectors, matrices, and multidimensional arrays. Column vectors are treated as Nx1 matrices, while row vectors are 1xN matrices. Vectors and matrices can be defined inline using bracket notation, as shown below.
a = [1;2;3] % a is a column vector containing the elements 1, 2, and 3
b = [2.5 3 8] % b is a row vector containing the elements 2.5, 3, and 8
c = [1, 2, 3] % c is a row vector containing 1, 2, and 3. Commas are optional
M = [1 2 3; 4 5 6; 7 8 9] % M is a 3x3 matrix with the first row containing 1, 2, and 3.
M = ['help1'; 'help2'; 'help3'] % M is a 3 by 5 character array
M = ['help1' 'help2' 'help3'] % M is the string help1help2help3
Note that semicolon denotes the end of a row, while comma separates row elements.
Indexing into Numeric Arrays
An element in an array variable is accessed with the following syntax:
var(index1, index2, ..., indexN)
where var is the name of the array, and var is an array of dimension N. The first element in a dimension has index 1. A colon may be used to indicate every element in the dimension. If only one indexing dimension is specified, then the array is linearly indexed, which means that the array is treated as a flat list (in column-wise order) and the N'th element of the list is returned.
 | Note: If only one indexing dimension is specified and it is a colon, then the array is returned as a single column vector with N elements, where N is equal to the number of elements in the array. |
The following example illustrates indexing into arrays.
M = [1 2 3; 4 5 6; 7 8 9] % M is a 3x3 matrix with the first row containing 1, 2, and 3.
a = M(2,1) % a equals 4
b = M(1,:) % b is the row vector [1,2,3]
c = M(:,[1;3]) % c is the 3x2 matrix [1,7; 2,8; 3,9]
d = M(6) % d equals 8
e = M(:) % e is the column vector [1;4;7;2;5;8;3;6;9]
M(1,1) = 5 % the element in the first row and first column of M is now 5
Vectors may also be used for specifying multiple elements in a dimension. The following example illustrates this:
M = [1,2,3; 4,5,6; 7,8,9]
a = M( [1; 3], [1; 2] ) % a is the matrix [1,2; 7,8]
Indexed Assignments
Mathematics Language supports assigning a value or values into arrays. If you assign data to elements outside the current dimensions of an array, the array is automatically resized to accomodate the new data, while any new elements in the array are initialized to zero.
When assigning from one array to another in the form A = B, the following rules must be obeyed:
- The number of subscripts specified for array B not including trailing 1's may not exceed the number of dimensions of B
- The number of non-scalar subscripts specified for A is equal to the number of non-scalar subscripts specified for B
- The length and order of all non-scalar subscripts specified for A is equal to the length and order of all non-scalar subscripts specified for B
The following code example illustrates various aspects of indexed assignments:
x(2,3) = 5; % x is a 2x3 matrix with the entry (2,3) equal to 5 and the other elements zero
x(:,2) = [11; 22] % the second column of x is now [11; 22]
x(1, [1 3]) = [100 200] % the first and third elements of the first row are now 100 and 200 respectively
% x is now equal to [100 11 200; 0 22 5]
x(1:6) = 1:6 % x is now equal to [1 3 5; 2 4 6]
x(1,1,2) = 23 % now x is a 2x3x2 array with x(1,1,2) equal to 23
Range Vectors
A range defines a row vector in either of the following two ways:
start:stop
start:stepsize:stop
where start, stepsize, and stop are expressions. If stepsize is left out, it is assumed to be 1. A range creates a row vector with the first element value being equal to start , each successive element being stepsize greater than the previous element, until stop is reached. Ranges may also be used to index into arrays and extract desired sub-arrays. The following example illustrates the use of ranges.
x = 1:10 % x is the row vector [1 2 3 4 5 6 7 8 9 10]
y = 1:2:10 % y is the row vector [1 3 5 7 9]
M = [1 2 3; 4 5 6; 7 8 9] % M is a 3x3 matrix with the first row containing 1, 2, and 3.
a = M(1:2, 2:3) % a is the 2x2 matrix: [2,3; 5,6]
b = M(1:2:3, :) % b is the 2x3 matrix: [1,2,3; 7,8,9]
Mathematical Operations on Arrays
Mathematical operations on arrays are supported. In general, any scalar operation or function may be performed on an array, and the operation will be performed on an element-by-element basis, producing a resulting array that has the same dimensions as the original array. The following example illustrates this:
x = [1,2; 3,4]
y = [1,1; 1,1]
z = x + y % z is the matrix [2 3; 4 5]
z = z - 1 % z is now the matrix [1 2; 3 4]
w = sin(z) % w is the matrix [sin(1), sin(2); sin(3),sin(4)]
Multiplication is a special-case operator. When using the multiplication operator on a matrix or vector, matrix-multiplication is assumed. To do an element-by-element multiplication, the .* operator is used. Here is an example:
x = [1 2; 3 4]
y = [1;1]
z = x * y %z is the vector [3; 7]
w = x .* [1 0;0 1] % w is the same matrix as x
To find out the dimensions of an array, use the size function. To find out how many elements are in an array, use the length function:
x = [1 2 3; 4 5 6]
x_dims = size(x) % x_dims is the vector [2 3]
num_elements = length(x) % num_elements is 6
Cell Arrays
Cell arrays are arrays that support each element having a differing data type. Each element in a cell array is called a cell. As an example, you may have a 1x3 cell array in which the first cell is a number, the second cell is a character array, and the third cell is a structure. Furthermore, elements of cell arrays may be cell arrays themselves. Cell arrays, just like numeric arrays, may have any number of dimensions. Cell array vectors and matrices may be defined inline as shown here:
X = { [1 2; 3 4] 'abc' 3j } % X is a 1x3 cell array containing a 2x2 real matrix, a 1x3 character array, and a complex scalar
Y = { {1 2}; {1 2; 3 4} } % Y is a 2x1 cell array containing a 1x2 cell array and a 2x2 cell array
Indexing into Cell Arrays
There are two ways to index into a cell array, described here:
M{indices} % returns the contents of the cell at the index specified by indices
M(indices) % returns the cell or cells at the index or indices specified by indices
Numeric arrays contained in cell arrays may be indexed inline as well:
M{2,3}(6) % returns 6th element of the array contained in the cell array M at location (2,3)
M{2,3}{2}(6) % returns 6th element of the array contained in the 2nd element of the cell array located in the cell array M at location (2,3)
The following example illustrates indexing into cell arrays.
M = { 1 'abcd' [2j 56; 3 j] {6 7} } % M is now a 1x4 cell array
a = M{1} % a equals 1
b = M{2} % b equals the 1x4 character array 'abcd'
c = M(2) % c equals a 1x1 cell array that contains 1 element: a 1x4 character array 'abcd'
d = M{3}(1,1) % d equals 2j
e = M{4} % e equals the cell array {6 7}
Structures
A structure is a data type with named fields. Each field has a name and a value. The value may be of any type, including a cell array or another structure. Structure arrays of any number of dimensions are supported. In a structure array, all structures in the array have the same field names.
Structures may be defined inline as shown here:
x.field1 = 23; % x is a structure with a field named "field1" with value 23
x.hello = {1 2}; % x now has another field named "hello" whose value is a 1x2 cell array
x(3).hello = 1; % x is now a 1x3 structure array with fields "field1" and "hello". The third element's hello field has value 1.
You may use the fieldnames function to determine what field names are in a structure. fieldnames returns a cell array of strings.
Structures may also be built using the struct function.
Network Communication and Instrument Control
The Math Language includes TCP/IP communication capabilities. This enables control of instruments.
When you create an equation set to do communication you will almost always want it to be not Auto-Calc. It should only calculate when specifically requested, otherwise every time an input variable changes it will rerun. It will also run on load. Turn off auto-calc by clicking the Check-Calculater toolbutton when viewing the equation set.
TCP/IP communication is done via the tcpip class, which is constructed using the tcpip function. A simple example follows (waitfor is a wait-for-character routine, PSAip contains the IP address string of an instrument, while PSASpciPort contains the port number to use for communications):
% - set up the tcpip pipe to the instrument
t = tcpip(PSAip, PSASpciPort) % build tcpip object using the PSA ip address and spci port
t.Terminator = 'CR/LF'; % set Terminator field
t.InputBufferSize = 100000; % use a big buffer
% - open the port
fopen(t)
% - set real data format
fprintf(t, 'form:data real,64')
% - swap byte order
fprintf(t, 'form:border swap')
% - read the trace
fprintf(t, 'trace? trace1') % tell it to send the first trace
a3 = waitfor(t, '#') % the # is followed by some count chars
% - get the # of count bytes
aBytecnt = fread( t, 1, 'uchar=>ushort')
tTotal = str2num( aBytecnt)
% - if valid # count bytes, read them
if tTotal > 0 && tTotal < 7 % we will never have more than 6 digits of stuff
ascCount = fread(t, tTotal, 'uchar=>ushort'); % read n count bytes
nCount = str2num( ascCount); % convert to numeric
nCount = nCount / 8; % convert to doubles at 8 bytes each
else
nCount = 0;
end
% - finally read the actual data
if nCount > 0
dInput = fread(t, nCount, 'double') % get nCount data values
setvariable('OutData', 'aOut', dInput) % save it in our dataset
end
% - close t so we rerun cleanly
fclose(t)
Analyzing the above example:
We start by creating a tcpip class object connected to our PSA device. PSAip=='127.0.0.1' or some valid ip address as a char array. PSAspciPort is an integer port number. Once the object is built, we set the terminator (for telnet in this case) and the input buffer size (plenty to avoid overflow).
We do fopen(t) which opens the socket connection.
Once connected you can use
fread - read nnn values from the data stream
fwrite - write nnn values to the data stream
fprintf - write a string to the data stream
fscanf - read a string from the data stream
When finished, close the socket by using fclose. If you are totally done with the socket you can use the Math Language clear function to remove the class object entirely.