LabTalk Scripting Guide E
LabTalk Scripting Guide E
OriginLab Corporation
One Roundhouse Plaza
Northampton, MA 01060
USA
(413) 586-2013
(800) 969-7720
Fax (413) 585-0126
www.OriginLab.com
Table of Contents
Table of Contents .....................................................................................................................iii
1 Getting Started with LabTalk ........................................................................................ 1
1.1 Hello World .................................................................................................................................... 1
1.2 Using = to Get Quick Output ......................................................................................................... 2
1.3 Other Ways to Execute Script ....................................................................................................... 2
1.4 Script Example .............................................................................................................................. 4
1.5 Where to Go from Here? ............................................................................................................... 6
2 Resources for Learning LabTalk .................................................................................. 7
2.1 Online Documentation ................................................................................................................... 7
2.2 Tutorials ......................................................................................................................................... 7
2.3 Script Examples ............................................................................................................................ 7
2.4 X-Function Script Examples .......................................................................................................... 7
2.5 LabTalk Forum .............................................................................................................................. 7
2.6 Training and Consulting ................................................................................................................ 7
3 Language Fundamentals .............................................................................................. 9
3.1 Language Fundamentals .............................................................................................................. 9
3.2 General Language Features ......................................................................................................... 9
3.3 Special Language Features ........................................................................................................ 44
3.4 LabTalk Script Precedence ......................................................................................................... 75
4 Calling X-Functions and Origin C Functions ..............................................................77
4.1 Calling X-Functions and Origin C Functions ............................................................................... 77
4.2 X-Functions ................................................................................................................................. 77
4.3 Origin C Functions ...................................................................................................................... 86
5 Running and Debugging LabTalk Scripts ...................................................................91
5.1 Running and Debugging LabTalk Scripts ................................................................................... 91
5.2 Running Scripts ........................................................................................................................... 91
5.3 Debugging Scripts ..................................................................................................................... 114
6 String Processing .......................................................................................................123
6.1 String Processing ...................................................................................................................... 123
6.2 String Variables and String Registers ....................................................................................... 123
6.3 String Processing ...................................................................................................................... 124
6.4 Converting Strings to Numbers ................................................................................................. 126
6.5 Converting Numbers to Strings ................................................................................................. 126
6.6 String Arrays.............................................................................................................................. 128
7 Workbooks Worksheets and Worksheet Columns ..................................................131
7.1 Workbooks Worksheets and Worksheet Columns.................................................................... 131
7.2 Workbooks ................................................................................................................................ 131
7.3 Worksheets ............................................................................................................................... 136
7.4 Worksheet Columns .................................................................................................................. 147
8 Matrix Books Matrix Sheets and Matrix Objects ......................................................159
8.1 Matrix Books Matrix Sheets and Matrix Objects ....................................................................... 159
8.2 Basic Matrix Book Operation..................................................................................................... 159
8.3 Matrix Sheets ............................................................................................................................ 161
8.4 Matrix Objects ........................................................................................................................... 162
9 Graphing .....................................................................................................................171
9.1 Graphing.................................................................................................................................... 171
9.2 Creating Graphs ........................................................................................................................ 171
9.3 Formatting Graphs .................................................................................................................... 174
iii
LabTalk Scripting Guide
iv
1 Getting Started with LabTalk
2. In this window, type the following text and then press Enter:
Note that when you press Enter, Origin adds a semicolon, ;, at the end of the line and
also executes that line of script.
To repeat the execution of a line of script, place the cursor anywhere within the line
and press Enter. If you place the cursor at the end of the line, you need to remove the
; before pressing Enter to execute that line of script.
Now let us see how to execute multiple lines of script from the script window:
1. With a workbook window active in Origin, open the Script Window
2. Type the following lines of script in the script window. At the end of each line, press Enter after
typing the ;. This will prevent execution of the line. We will later execute all lines together.
beginning of the script, then hold down the Shift key, and use the arrow keys to highlight all
lines.
4. Press Enter to execute all selected lines of script. Depending on the workbook that was active,
the output in the script window will be similar to the following text:
1
LabTalk Scripting Guide
In the above example, we used the %H String Register that holds the currently active window name
(which could be a workbook, a matrix, or a graph). We then used the page and wks LabTalk Objects
to get the number of sheets in the book and the number of columns in the sheet. The $() is a
substitution notations which tells Origin to evaluate the expression within the () and return its value.
If you are typing in multiple lines of script in the Script Window, you can add a ; at the
end of a line and then press Enter to avoid execution of the line. This allows you to
type in multiple lines without executing each line. You can then select all lines and
press Enter to execute them all.
2
Getting Started with LabTalk
2. This opens Code Builder, Origin's native script editor. The file being edited is called
Custom.ogs. The code has one section, [Main], and contains one line of script:
[Main]
type -b $General.Userbutton;
3. Replace that line with the following:
[Main]
type -b "Hello World";
5. Now go back to the Origin application window and click the button.
Origin will again output the text Hello World, but this time, because of the -b switch used with the
type command, the text will be presented in a pop-up window.
Organizer dialog.
2. Make the Add Custom Menu tab active. Then right-click inside the left panel and select New
3. In the right panel, enter a name for Popup Text, such as My Menu. then click outside of the
edit box.
4. Select My Menu from the left panel, and then right click on it, and select Add Item from the
context menu.
5. In the right panel, change the Item Text to Hello World, then add the following script to the
as Default menu. In the file dialog that opens, press Save to save the file with the default name
3
LabTalk Scripting Guide
7. A new menu named My Menu should now appear in the menu bar, to the left of the Window
menu. Click on this new menu item, and then click on the Hello World entry in the drop-down.
2. Press the Text Tool button ( ) in the Tools Toolbar, and then click on the newly created
graph and type the text My Button. Then click outside the text to finish editing the text.
3. Right click on the text to bring up the context menu, and then select Programming Control to
4. In the dialog, select Button Up from the Script, Run After: drop-down list, and then type the
4
Getting Started with LabTalk
The above process will load the file path and name into a variable named fname$. You can examine
the value of this variable by typing:
fname$=
Now let's import this files into the active workbook. We will use the impasc X-Function with options to
control naming, so that the file name does not get assigned to the workbook:
impasc Options.Names.FNameToBk:=0
Now we want to perform some data processing of the Position column. We first define a range
variable to point to this column.:
range rpos = "Position"
Since the column we select is also the 4th column in the current worksheet, we can also use index
number to specify it.
range rpos = 4
You can check what range variables are currently defined, using this command:
list a
We now normalize the column so that the values go from 0 to 100. To check what X-Functions are
available for normalization, we can use the command:
lx *norm*
The above command will dump X-Functions where the name contains norm. There are several X-
Functions for normalizing data. For our current purpose we will use the rnormalize X-Function.
To get help on the syntax for this particular X-Function, you can type:
rnormalize -h
to dump the information, or type:
help rnormalize
to open the help file.
Let us now normalize the position column:
rnormalize irng:=rpos method:=range100 orng:=<input>
The normalized data will be placed in the same column, replacing the original data, as we set the
output range variable orng to be <input>.
When using X-Functions, you can leave out the variable names, if they are specified in the correct
order. The above line of code can therefore be written as:
rnormalize rpos range100 orng:=<input>
The reason we still specified the name orng is because there are other variables that precede this
particular variable, which are not relevant to our current calculation and were therefore not included in
the command.
Now let's do some changes to the folder in the project. There are several X-Functions for managing
project folders, and we will use some of them:
// Get the name of the current worksheet
string name$ = wks.name$;
// go to root folder
pe_cd ..;
// rename Folder1 to be the same as worksheet
pe_rename Folder1 name$;
Now let's list all the sub folders and workbooks under the root folder:
pe_dir
Finally, let's save the Origin Project to the User Files Folder. The location of the user files folder is
stored in the string register %Y. You can examine where your User Files Folder is by checking this
variable:
%Y =
Now let's use the save command to save our project to User Files Folder, with the name
MyProject.opj.
save %yMyProject
In the above command %Y will be replaced with the User Files Folder path, and thus our project will
be saved in the correct location.
5
LabTalk Scripting Guide
6
2 Resources for Learning LabTalk
Besides the content provided in this guide, the following resources are available for learning LabTalk.
2.2 Tutorials
Several LabTalk tutorials are shipped with Origin. These are accessible from the Help menu.
7
3 Language Fundamentals
Programming Syntax
Operators
Macros
9
LabTalk Scripting Guide
Functions
Integer Integers
Constant Numeric data type that value cannot be changed once declared
Graphic Object Objects like labels, arrows, lines, and other user-created graphic elements
Numeric
LabTalk supports three numeric data types: double, int, and const.
1. Double: double-precision floating-point number; this is the default variable type in Origin.
2. Integer: integers (int) are stored as double in LabTalk; truncation is performed during
assignment.
3. Constant: constants (const) are a third numeric data type in LabTalk. Once declared, the value
once declared. It means that the constant will be saved as "System Variable" and available
10
Language Fundamentals
LabTalk does not have a complex datatype. A column can be set as Numeric Complex and
basic operations (+,-,*,/) work between columns or using literal values. While functions are
available for extracting real and imaginary parts of a complex column value or literal
Values such as 0.0, NANUM (missing value) and values between -1.0E-290 to 1.0E-
290 will be evaluated to be False in logic statement. For instance, LabTalk command
will return a value 0 (False) instead of 1 (True).
type $(-1e-290?1:0); // Returns 0 (False)
type $(1/0?1:0); // Returns 0 (False), where 1/0 == NANUM
Dataset
When you declare a dataset variable it is stored internally as a local, temporary loose dataset.
Temporary means it will not be saved with the Origin project; loose means it is not affiliated with a
particular worksheet. Temporary loose datasets are used for computation only, and cannot be used
for plotting.
The following brief example demonstrates the use of this data type (Dataset type declaration and $
Substitution Notation are used in this example):
// Declare a dataset 'aa' with values from 1-10,
// with an increment of 0.2:
dataset aa={1:0.2:10};
// Declare integer 'nSize',// and assign to it the length of the new array:
int nSize = aa.GetSize();
11
LabTalk Scripting Guide
When you create a dataset by vector assignment (without declaration) or by using the Create
(Command) it becomes a project level loose dataset, which can be used for computation or plotting.
Create a project-level loose dataset by assignment,
bb = {10:2:100}
Or by using the Create command:
create %(strWks$) -wdn 10 aa bb;
For more on project-level and local-level variables see the section below on Scope of Variables.
For more on working with Datasets, see Datasets.
For more on working with %( ), see Substitution Notation.
String
LabTalk supports string handling in two ways: string variables and string registers.
String Variables
String variables may be created by declaration and assignment or by assignment alone (depending
on the desired variable scope), and are denoted in LabTalk by a name comprised of continuous
characters (see Naming Rules below) followed by a $-sign (i.e., stringName$):
// Create a string with local/session scope by declaration and assignment
12
Language Fundamentals
String Registers
Strings may be stored in String registers, denoted by a leading %-sign followed by a letter of the
alphabet (i.e., %A-%Z). String Registers are always global in scope.
/* Assign to the string register %A the string "Hello World": */
%A = "Hello World";
For current versions of Origin, we encourage the use of string variables for working
with strings, as they are supported by several useful built-in methods; for more, see
String(Object). If, however, you are already using string registers, see String Registers
for complete documentation on their use.
StringArray
The StringArray data type handles arrays of strings in the same way that the Datasets data type
handles arrays of numbers. Like the String data type, StringArray is supported by several built-in
methods; for more, see StringArray (Object).
The following example demonstrates the use of StringArray:
// Declare string array named "aa",
// and use built-in methods Add, and GetSize:
StringArray aa; // aa is an empty string array
aa.Add("Boston"); // aa now has one element: "Boston"
aa.Add("New York"); // aa has a second element: "New York"
Range
The range data type allows functional access to many data-related Origin objects, referring to a
specific region in a workbook, worksheet, graph, layer, or window.
The general syntax is:
range rangeName = [WindowName]LayerNameOrIndex!DataRange[subRange]
which can be made specific to data in a workbook, matrix, or graph:
range rangeName =
[BookName]SheetNameOrIndex!ColumnNameOrIndex[RowBegin:RowEnd]
range rangeName =
[MatrixBookName]MatrixSheetNameOrIndex!MatrixObjectNameOrIndex[CellBegin:CellEnd]
range rangeName =[GraphName]LayerNameOrIndex!DataPlotIndex[RowBegin:RowEnd]
The special syntax [??] is used to create a range variable to access a loose dataset.
For example:
// Access Column 3 on Book1, Sheet2:
range cc = [Book1]Sheet2!Col(3);
// Access second curve on Graph1, layer1:
range ll = [Graph1]Layer1!2;
// Access second matrix object on MBook1, MSheet1:
range mm = [MBook1]MSheet1!2;
// Access loose dataset tmpdata_a:
13
LabTalk Scripting Guide
range xx = [??]!tmpdata_a;
Notes:
CellRange can be a single cell, (part of) a row or column, a group of cells, or a non-contiguous
selection of cells.
Worksheets, Matrix Sheets, and Graph Layers can each be referenced by name or index.
You can define a range variable to represent an origin object, or use range directly as an X-
Function argument.
Many more details on the range data type and uses of range variables can be found in the
Range Notation.
Tree
LabTalk supports the standard tree data type, which emulates a tree structure with a set of branches
and leaves. The branches contain leaves, and the leaves contain data. Both branches and leaves are
called nodes.
Leaf: A node that has no children, so it can contain a value
Branch: A node that has child nodes and does not contain a value
A leaf node may contain a variable that is of numeric, string, or dataset (vector) type.
Trees are commonly used in Origin to set and store parameters. For example, when a dataset is
imported into the Origin workspace, a tree called options holds the parameters which determine how
the import is performed.
Specifically, the following commands import ASCII data from a file called "SampleData.dat", and set
values in the options tree to control the way the import is handled. Setting the ImpMode leaf to a
value of 4 tells Origin to import the data to a new worksheet. Setting the NumCols leaf (on the Cols
branch) to a value of 3 tells Origin to only import the first three columns of the SampleData.dat file.
string str$ = system.path.program$ + "Samples\Graphing\Group.dat";
impasc fname:=str$
/* Start with new sheet */
options.ImpMode:=4
/* Only import the first three columns */
options.Cols.NumCols:=3;
Declare a tree variable named aa:
// Declare an empty tree
tree aa;
// Tree nodes are added automatically during assignment:
aa.bb.cc=1;
aa.bb.dd$="some string";
// Declare a new tree 'trb' and assign to it data from tree 'aa':
tree trb = aa;
Check the existence of a tree, and the existence of the leaf and branch on the tree
Tree tr;
exsit(tr)=; //will return 24 if this tree exists; Otherwise, return 0.
tr.a.b=1;
tr.a@=; /// get 2, for branch
tr.a.b@=; /// get 1, for leaf
tr.a.b1@=;/// get 0, not valid
14
Language Fundamentals
The tree data type is often used in X-Functions as both an input and output data structure. For
example:
// Put import file info into 'trInfo'.
impinfo t:=trInfo;
Tree nodes can be strings. The following example shows how to copy a treenode with string data to
worksheet columns:
//Import the data file into worksheet
newbook;
string fn$=system.path.program$ + "\samples\statistics\automobile.dat";
impasc fname:=fn$;
tree tr;
//Perform statistics on a column and save results to a tree variable
discfreqs irng:=2 rd:=tr;
// Assign strings to worksheet column.
newsheet name:=Result;
col(1) = tr.freqcount1.data1;
col(2) = tr.freqcount1.count1;
Tree nodes can also be vectors. Prior to Origin 8.1 SR1 the only way to access a vector in a Tree
variable was to make a direct assignment, as shown in the example code below:
tree tr;
// If you assign a dataset to a tree node,
// it will be a vector node automatically:
tr.a=data(1,10);
// A vector treenode can be assigned to a column:
col(1)=tr.a;
// A vector treenode can be assigned to a loose dataset, which is
// convenient since a tree node cannot be used for direct calculations
dataset temp=tr.a;
// Perform calculation on the loose dataset:
col(2)=temp*2;
You can access elements of a vector tree node directly, with statements such as:
// Following the example immediately above,
col(3)[1] = tr.a[3];
that assigns the third element of vector tr.a to the first row of column 3 in the current worksheet.
You can also output analysis results to a tree variable, like the example below.
newbook;
//Import the data file into worksheet
string fn$=system.path.program$ + "\samples\Signal
Processing\fftfilter1.dat";
impasc fname:=fn$;
tree mytr;
//Perform FFT and save results to a tree variable
fft1 ix:=col(2) rd:=mytr;
page.active=1;
col(3) = mytr.fft.real;
col(4) = mytr.fft.imag;
More information on trees can be found in the chapter on Origin Projects,Accessing Metadata
section.
Graphic Objects
The new LabTalk variable type GObject allows the control of graphic objects in any book/layer.
15
LabTalk Scripting Guide
3.2.2.2 Variables
A variable is simply an instance of a particular data type. Every variable has a name, or identifier,
which is used to assign data to it, or access data from it. The assignment operator is the equal sign
(=), and it is used to simultaneously create a variable (if it does not already exist) and assign a value
to it.
Variable, dataset, command, and macro names are referred to generally as identifiers. When
assigning identifiers in LabTalk:
Use any combination of letters and numbers, but note that:
o the underscore character "_" has a special meaning in dataset names and should be
avoided.
Use the Exist (Function) to check if an identifier is being used to name a window, macro, tool,
dataset, or variable.
Note that several common identifiers are reserved for system use by Origin, please see System
The @ppv system variable controls how Origin handles naming conflicts between project, session,
and local variables. Like all system variables, @ppv can be changed from script anytime and takes
immediate effect.
Variable Description
16
Language Fundamentals
This is the DEFAULT option and allows both session variables and local variables to
@ppv=0 use existing project variable names. In the event of a conflict, session or local
variables are used.
This option makes declaring a session variable with the same name as an existing
project variable illegal. Upon loading a new project, session variables with a name
@ppv=1
conflict will be disabled until the project is closed or the project variable with the
same name is deleted.
This option makes declaring a local variable with the same name as an existing
project variable illegal. Upon loading of new project, local variables with a name
@ppv=2
conflict will be disabled until the project is closed or the project variable with the
same name is deleted.
This is the combination of @ppv=1 and @ppv=2. In this case, all session and local
@ppv=3 variables will not be allowed to use project variable names. If a new project is
loaded, existing session or local variables of the same name will be disabled.
Use the LabTalk commands list and del for listing variables and deleting variables, respectively.
/* Use the LabTalk command "list" with various options to list
variables; the list will print in the Script Window by default: */
Session variables
Local variables
17
LabTalk Scripting Guide
In practical terms this means that (a) you can have multiple variables of the same name and (b) when
that is the case, the value returned at any given time is dependent upon the current scope (see
Session and Local variables, below).
Project Variables
Project variables are saved with the Origin Project (*.OPJ). Project variables are said to have
Project scope.
Project variables are automatically created without declaration for variables of type double,
All other variable types must be declared, which makes their default scope either Session or
Local. Note that you can make Local variables available as Session variables, using the @glob
Session Variables
Session variables are not saved with the Origin Project, and are available in the current Origin
session across projects. Thus, once a Session variable has been defined, they exist until the
Origin application is terminated or the variable is deleted. Session variables are defined with
variable declarations:
18
Language Fundamentals
Local Variables
Local variables exist only within the current scope of a particular script.
Script-level scope exists for scripts:
enclosed in curly braces {},
Local variables are declared and assigned values in the same way as Session variables:
loop(i,1,10){
double a = 3.5;
const e = 2.718;
// some other lines of script...
}
// "a" and "e" exist only inside the code enclosed by {}
It is possible to have Local variables with the same name as Session variables or Project variables. In
this case, the Local variable takes precedence over the Session or Project variable of the same
name, within the scope of the script. For example, if you run the following script (Please refer to Run
LabTalk Script From Files for details on how to run such script):
[Main]
double aa = 10;
type "In the main section, aa equals $(aa)";
run.section(, section1);
run.section(, section2);
[section1]
double aa = 20;
type "In section1, aa equals $(aa)";
[section2]
// This section does not declare a local variable named 'aa'.
// A variable named 'aa' will be searched for in the following order:
// If a Session variable named 'aa' exists then it will be used.
// Else if a Project variable named 'aa' exists then it will be used.
// Else if this section is called from another section and the caller
// section declared a local variable named 'aa' then it will be used.
// Else 'aa' will be a missing value.
type "In section2, aa equals $(aa)";
Origin will output:
In the main section, aa equals 10
In section1, aa equals 20
In section2, aa equals 10
19
LabTalk Scripting Guide
At times you may want to define variables or functions in a *.OGS file, but then be able to use them
from the Script Window, in a text label, etc. (normally, the Local variable or function ceases to exist
when the OGS runs to completion). To do so, set the value of the @glob system variable to 1
(default value is 0). This makes Local variables and functions in the OGS file available in the Session:
[Main]
@glob = 1;
// the following declarations become available in the session
range a = 1, b= 2;
if(a[2] > 0)
{
// begin a local scope
range c = 3; // this declaration is still available in the session
}
Upon exiting the *.OGS, the @glob variable is automatically restored to its default value, 0.
Note that one can also control a block of code by placing @glob at the beginning and end, as in:
@glob=1;
double alpha=1.2;
double beta=2.3;
Function double myPeak(double x, double x0)
{
double y = 10*exp(-(x-x0)^2/4);
return y;
}
@glob=0;
double gamma=3.45;
In the above script, variables alpha, beta, and the user-defined function myPeak will be available in
the session. The variable gamma will not be available because it was declared after @glob was
returned to its default value of 0.
Data Declared
Where Defined Example Lifetime
Type ?
Script Window
Command
Window
While Origin runs.
const av =
Constan consta Yes All constants are
OGS File 6.022×10
2
t nt (const) 3 saved in
;
orgvar.ogs.
Various GUI
dialogs
20
Language Fundamentals
Window
OGS File
Various GUI
dialogs
Script Window
double av While the session
Command
Session all = runs.
Yes 2
Variable types 6.022×10 NOT saved with
Window 3
; the OPJ.
OGS file
double av
Various GUI
Local all = While the script
Yes 2
Variable types 6.022×10 runs.
dialogs 3
;
OGS file
While the session
Local @glob=1;
runs.
Variable Various GUI double av
all Can be saved with
as Yes =
types 2 the OPJ (see
Session dialogs 6.022×10
3 ProjectEvents.OG
Variable ;
S).
21
LabTalk Scripting Guide
the open parenthesis signifies the beginning of a single word, and the close parenthesis signifies the
end of the word.
Statement Types
Comments
Statement Types
Macro Statements
Command Statements
Arithmetic Statement
Function Statements
Assignment Statements
When new values are assigned to an existing data object, the following conventions apply:
If LHS is a dataset and expression is a scalar, every value in LHS is set equal to expression.
22
Language Fundamentals
If LHS is a numeric variable, then expression must evaluate into a scalar. If expression
evaludate into a dataset, LHS retrieves the first element of the dataset.
If both LHS and expression represent datasets, each value in LHS is set equal to the
If the LHS is the object.property notation, with or without $ at the end, then this notation is
used to set object properties, such as the number of columns in a worksheet, like wks.ncols=3;
Macro Statements
Macros provide a way to alias a script, that is, to associate a given script with a specific name. This
name can then be used as a command that invokes the script.
For more information on macros, see Macros
Command Statements
The third statement type is the command statement. LabTalk offers commands to control or modify
most program functions.
Each command statement begins with the command itself, which is a unique identifier that can be
abbreviated to as little as two letters (as long as the abbreviation remains unique, which is true in
most cases). Most commands can take options (also known as switches), which are single letters that
23
LabTalk Scripting Guide
modify the operation of the command. Options are always preceded by the dash "-" character.
Commands can also take arguments. Arguments are either a script or a data object. In many cases,
options can also take their own arguments.
Command statements take the general form:
command [option] [argument(s)];
The brackets [] indicate that the enclosed component is optional; not all commands take both options
and arguments. The brackets are not typed with the command statement (they merely denote an
optional component).
Methods (Object) are another form of command statement. They execute immediate actions relating
to the named object. Object method statements use the following syntax:
ObjectName.Method([options]);
For example:
The following script adds a column named new to the active worksheet and refreshes the window:
wks.addcol(new);
doc -uw;
The following examples illustrate different forms of command statements:
Integrate the dataset myData from zero.
integ myData;
Adding the -r option and its argument, baseline, causes myData to be integrated from a reference
curve named baseline.
integ -r baseline myData;
The repeat command takes two arguments to execute:
1. the number of times to execute, and
This command statement prints "Hello World" in a dialog box three times.
repeat 3 {type -b "Hello World"}
Arithmetic Statement
operator can be +, -, *, /, or ^.
The result of the calculation is put into dataObject1. Note that dataObject1 cannot be a function. For
example, col(3) + 25 is an illegal usage of this statement form.
The following examples illustrate different forms of arithmetic statements:
If myData is a dataset, this divides each value in myData by 10.
myData / 10;
Subtract otherData from myData, and put the result into myData. Both datasets must be Y or Z
datasets (see Note).
myData - otherData;
If A is a variable, increment A by 1. If A is a dataset, increment each value in A by 1.
A + 1;
24
Language Fundamentals
Note: There is a difference between using datasets in arithmetic statements versus using datasets in
assignment statements. For example, data1_b + data2_b is computed quite differently from data1_b
= data1_b + data2_b. The latter case yields the true point-by-point sum without regard to the two
datasets' respective X-values. The former statement, data1_b + data2_b, adds the two data sets as
if each were a curve in the XY-plane. If therefore, data1_b and data2_b have different associated X-
values, one of the two series will require interpolation. In this event, Origin interpolates based on the
first dataset's (data1_b in this case) X-values.
Function Statements
The function statement begins with the characteristics of a function -- an identifier -- followed by a
quantity, enclosed by parentheses, upon which the function acts.
An example of a function statement is:
sum(dataset);
For more on functions in LabTalk, see Functions.
Like the C programming language, LabTalk uses semicolons to separate statements. In general,
every statement should end with a semicolon. However, the following rules clarify semicolon usage:
Do not use a semicolon when executing a single statement script in the Script window.
o The interpreter automatically places a semicolon after the statement to indicate that it
In the following example, please note the differences between the three type command:
if (m>2) {type "hello";} else {type "goodbye"}
type "the end";
The above can also be written as:
if (m>2) {type "hello"} else {type "goodbye"}
type "the end";
or
if (m>2) {type "hello"} else {type "goodbye"};
type "the end";
You can place a ';' in front of a script to delay its execution. This is often needed when you need to
run a script inside a button that will delete the button itself, like to issue window closing or new project
commands. For example, placing the following script inside a button will possibly lead to a crash
// button to close this window
type "closing this window";
win -cn %H;
25
LabTalk Scripting Guide
3.2.3.5 Comments
LabTalk script accepts two comment formats:
Use the "//" character to ignore all text from // to the end of the line. For example:
type "Hello World"; //Place comment text here.
Use the combination of "/*" and "*/" character pairs to begin and end, respectively, any block of code
or text that you do not want executed. For example:
type Hello /* Place comment text here,
or a line of code:
and even more ... */
World;
Note: Use the "#!" characters to begin debugging lines of script. The lines are only executed if
system.debug = 1.
26
Language Fundamentals
The recognition order can have significant effect on script functions. For example, the following
assignment statement:
type = 1;
assigns the value 1 to the variable type. This occurs even though type is (also) a LabTalk command,
since assignments come before commands in recognition order. However, since commands precede
arithmetic expressions in recognition order, in the following statement:
type + 1;
the command is carried out first, and the string, + 1, prints out.
The statements are executed in the order received, using the following evaluation priority
Assignment statements: String variables to the left of the assignment operator are not
expressed unless enclosed by parentheses. Otherwise, all string variables are expressed, and
Command statements: If a command is a raw string, it is not sent to the substitution processor.
3.2.4 Operators
3.2.4.1 Introduction
LabTalk supports assignment, arithmetic, logical, relational, and conditional operators:
Arithmetic Operators + - * / ^ & |
String Concatenation +
Assignment Operators = += -= *= /= ^=
Conditional Operator ?:
These operations can be performed on scalars and in many cases they can also be performed on
vectors (datasets). Origin also provides a variety of built-in numeric, trigonometric, and statistical
functions which can act on datasets.
When evaluating an expression, Origin observes the following precedence rules:
1. Exposed assignment operators (not within brackets) are evaluated.
4. The (>, >=, <, <=) relational operators are evaluated, then the (== and !=) operators.
27
LabTalk Scripting Guide
+ Addition
- Subtraction
* Multiplication
/ Division
Define a constant
col(c) = log(col(c));
28
Language Fundamentals
col(c) = 10^(col(c));
= Simple assignment.
+= Addition assignment.
-= Subtraction assignment.
*= Multiplication assignment.
/= Division assignment.
^= Exponential assignment.
These operations can be performed on scalars and on vectors (datasets). For more information on
scalar and vector calculations, see Performing Calculations in this topic.
The following example illustrates the use of the -= operator.
In this example, 5 is subtracted from the value of A and the result is assigned to A:
A -= 5;
In the next example, each value in Data1_B is divided by the corresponding value in Book1_A, and
the resulting values are assigned to Book1_B.
Book1_B /= Book1_A;
29
LabTalk Scripting Guide
In addition to these assignment operators, LabTalk also supports the increment and decrement
operators for scalar calculations (not vector).
Operator Use
== Equal to
!= Not equal to
&& And
|| Or
An expression involving logical or relational operators evaluates to either true (non-zero) or false
(zero). Logical operators are almost always found in the context of Conditional and Loop Structures.
Numeric Comparison
The most common comparison is between two numeric values. Generally, at least one is a variable.
For instance:
if aa<3 type "aa<3";
Or, both items being compared can be variables:
if aa<=bb type "aa<=bb";
It is also possible, using parentheses, to make multiple comparisons in the same logical statement:
if (aa<3 && aa<bb) type "aa is lower";
String Comparison
You can use the == and != operators to compare two strings. String comparison (rather than numeric
comparison) is indicated by open and close double quotations (" ") either before, or after, the
operator. The following script determines if the %A string is empty:
30
Language Fundamentals
Scalar Calculations
31
LabTalk Scripting Guide
You can use LabTalk to express a calculation and store the result in a numeric variable. For example,
consider the following script:
inputVal = 21;
myResult = 4 * 32 * inputVal;
The second line of this example performs a calculation and creates the variable, myResult. The value
of the calculation is stored in myResult.
When a variable is used as an operand, and will store a result, shorthand notation can be used. For
example, the following script:
B = B * 3;
could also be written:
B *= 3;
In this example, multiplication is performed with the result assigned to the variable B. Similarly, you
can use +=, -=, /=, and ^=. Using shorthand notation produces script that executes faster.
Vector Calculations
In addition to performing calculations and storing the result in a variable (scalar calculation), you can
use LabTalk to perform calculations on entire datasets as well.
Vector calculations can be performed in one of two ways: (1) strictly row-by-row, or (2) using linear
interpolation.
Row-by-Row Calculations
Vector calculations are always performed row-by-row when you use the two general notations:
datasetB = scalarOrConstant <operator> datasetA;
datasetC = datasetA <operator> datasetB;
This is the case even if the datasets have a different numbers of elements. Suppose there are three
empty columns in your worksheet: A, B, and C. Run the following script:
col(a) = {1, 2, 3};
col(b) = {4, 5};
col(c) = col(a) + col(b);
The result in column C will be {5, 7, --}. That is, Origin outputs a missing value for rows in which one
or both datasets do not contain a value.
Vector calculations can also involve a scalar. In the above example, type:
col(c) = 2 * col(a);
Column A is multiplied by 2 and the results are put into the corresponding rows of column C.
Instead, execute the following script (assuming newData does not previously exist):
newData = 3 * Book1_A;
A temporary dataset called newData is created and assigned the result of the vector operation.
Origin supports interpolation through range notation and X-Functions such as interp1 and interp1xy.
Please refer to Interpolation for more details.
Decision structures, which allow the program to perform different sets of actions depending on
the circumstances.
32
Language Fundamentals
Repeat
The repeat loop is used when a set of actions must be repeated without any alterations.
Syntax: repeat value {script};
Execute script the number of times specified by value, or until an error occurs, or until the break
command is executed.
For example, the following script types the string three times:
repeat 3 { type "line of output"; };
Loop
The loop loop is used when a single variable is being incremented with each successive loop.
Syntax: loop (variable, startVal, endVal) {script};
A simple increment loop structure. Initializes variable with the value of starVal. Executes script.
Increments variable and tests if it is greater than endVal. If it is not, executes script and continues to
loop.
For example, the following script outputs numbers from 1 to 4:
loop (ii, 1, 4) {type "$(ii)";};
Note: The loop command provides faster looping through a block of script than does the for
command. The enhanced speed is a result of not having to parse out a LabTalk expression for the
condition required to stop the loop.
Doc -e
The doc -e loop is used when a script is being executed to affect objects of a specific type, such as
graph windows. The doc -e loop tells Origin to execute the script for each instance of the specified
object type.
Syntax: doc -e object {script};
The different object types are listed in the document command.
For example, the following script prints the windows title of all graph windows in the project:
doc -e P {%H=}
For
33
LabTalk Scripting Guide
when expression2 is found to be false (zero). Any expression can consist of multiple statements,
each separated by a comma.
For example, the following script output numbers from 1 to 4:
for(ii=1; ii<=4; ii++)
{
type "$(ii)";
}
Note: The loop command provides faster looping through a block of script.
The if-else command is used when one script must be executed if a condition is true (non-
The switch command is used when more than two possibilities are included in a script.
If, If-Else
Syntax:
1. if (testCondition) sentence1; [else sentence2;]
Evaluate testCondition and if true, execute script1. Expressions without conditional operators are
considered true if the result of the expression is non-zero.
If the optional else is present and testCondition is false (zero), then execute script2. There should be
a space after the else. Strings should be quoted and string comparisons are not case sensitive.
Single statement script arguments should end with a semicolon. Multiple statement script arguments
must be surrounded by braces {}. Each statement within the braces should end with a semicolon. It is
not necessary to follow the final brace of a script with a semicolon.
For example, the following script opens a message box displaying "Yes!":
%M = test;
if (%M == "TEST") type -b "Yes!";
else type -b "No!";
The next script finds the first point in column A that is greater than -1.95:
newbook;
col(1)=data(-2,2,0.01);
val = -1.95;
get col(A) -e numpoints;
for(ii = 1 ; ii <= numpoints ; ii++)
{
// This will terminate the loop early if true
if (Col(A)[ii] > val) break;
}
if(ii > numpoints - 1)
ty -b No number exceeds $(val);
else
type -b The index number of first value > $(val) is $(ii)
34
Language Fundamentals
Switch
The switch command is used when more than two possibilities are included in a script. For example,
the following script returns b:
ii=2;
switch (ii)
{
case 1:
type "a";
break;
case 2:
type "b";
break;
case 3:
type "c";
break;
default:
type "none";
break;
}
LabTalk provides a break command. When executed, this causes an exit from the loop and,
optionally, the script. This is often used with a decision structure inside a loop. It is used to protect
against conditions which would invalidate the loop test conditions. The break command can be used
to display a progress status dialog box (progress bar) to show the current progress through the loop.
Exit
The exit command prompts an exit from Origin unless a flag is previously set to prevent the exit.
Continue
The continue command can be used within loops. When executed, the remainder of the loop is
ignored and the interpreter jumps to the next iteration of the loop. This is often used with a decision
structure inside a loop and can exclude illegal values from being processed by the loop script.
For example, in the following for loop, continue skips the type statement when ii is less than zero.
for (ii = -10; ii <= 10; ii += 2)
{
if (ii < 0)
continue;
type "$(sqrt(ii))";
}
35
LabTalk Scripting Guide
In addition to entering the script in the Label Control dialog, you can also save it as an Origin Script
(OGS) file. An Origin script file is an ASCII text file which consists of a series of one or more LabTalk
statements. Often, you can divide the statements into sections. A section is declared by a section
name surrounded by square brackets on its own line of text:
[SectionName]
Scripts under a section declaration belong to that section until another section declaration is met. A
framework for a script with sections will look like the following:
...
Scripts;
...
[Section 1]
...
Scripts;
...
[Section 2]
...
Scripts;
...
Scripts will be run in sequence until a new section flag is encountered, a return statement is executed
or an error occurs. To run a script in sections, you should use the
run.section(FileName, SectionName)
command. When filename is not included, the current running script file is assumed, for example:
run.section(, Init)
The following script illustrates how to call sections in an OGS file:
type "Hello, we will run section 2";
run.section(, section2);
[section1]
type "This is section 1, End the script.";
[section2]
type "This is section 2, run section 1.";
run.section(, section1);
To run the script, you can save it to your Origin user folder as test.ogs, and type the following in the
command window:
run.section(test);
If code in a section could cause an error condition which would prematurely terminate a section, you
can use a variable to test for that case, as in:
[Test]
SectionPassed = 0;
// Here is where code that could fail can be run
...
SectionPassed = 1;
If the code failed, then SectionPassed will still have a value of 0. If the code succeeded, then
SectionPassed will have a value of 1.
3.2.6 Macros
3.2.6.1 Definition of the Macros
The command syntax,
define macroName {script}
36
Language Fundamentals
defines a macro called macroName, and associates it with the given script. MacroName can then be
used like a command, and invokes the given script.
For example, the following script defines a macro that uses a loop to print a text string three times.
def hello
{
loop (ii, 1, 3)
{ type "$(ii). Hello World"; }
};
Once the hello macro is defined, typing the word hello in the Script window results in the printout:
1. Hello World
2. Hello World
3. Hello World
Once a macro is defined, you can also see the script associated with it by typing
define macroName;
37
LabTalk Scripting Guide
}
else
{
type "The first argument passed was %1.";
type "The second argument passed was %2.";
type "The third argument passed was %3.";
}
};
If you define the TypeArgs macro as in the example, and then type the following in the Script window:
TypeArgs One;
Origin returns the following to the Script window:
Error! You must pass 3 arguments!
If you define the TypeArgs macro as in the example, and then type the following in the Script window:
TypeArgs One (This is argument Two) Three;
Origin returns the following to the Script window:
The first argument passed was One.
The second argument passed was This is argument Two.
The third argument passed was Three.
3.2.7 Functions
Functions are the core of almost every programming language; the following introduces function
syntax and use in LabTalk.
38
Language Fundamentals
2. Both arguments and return values support string, double, int, dataset, and tree data types.
The default argument type is double. The default return type is int.
3. By default, arguments of user-defined functions are passed by value, meaning that argument
values inside the function are NOT available outside of the function. However, passing
arguments by reference, in which changes in argument values inside the function WILL be
39
LabTalk Scripting Guide
}
// Here we count Fridays
iVal = iCountDays(col(1),6); // 6 is Friday in weekday(data, 1) sense
iVal=;
Functions can also return datasets ..
// Get only negative values from a dataset
function dataset dsSub(dataset ds1)
{
dataset ds2;
int iRow = 1;
for(int ii = 1 ; ii <= ds1.GetSize() ; ii++)
{
if(ds1[ii] < 0)
{
ds2[iRow] = ds1[ii];
iRow++;
}
}
return ds2;
}
// Assign all negative values in column 1 to column 2
col(2) = dsSub(col(1));
or strings ..
// Get all values in a dataset where a substring occurs
function string strFind(dataset ds, string strVal)
{
string strTest, strResult;
for( int ii = 1 ; ii <= ds.GetSize() ; ii++ )
{
strTest$ = ds[ii]$;
if( strTest.Find(strVal$) > 0 )
{
strResult$ = %(strResult$)%(CRLF)%(strTest$);
}
}
return strResult$;
}
// Gather all instances in column 3 where "hadron" occurs
string MyResults$ = strFind(col(3),"hadron")$; // Note ending '$'
MyResults$=;
This example demonstrates a function that returns a tree node value as an int (one element of a tree
variable). In addition, passing by reference is illustrated using the REF keyword.
// Function definition:
Function int GetMinMax(range rr, ref double min, ref double max) {
stats rr;
//after running the stats XF, a LabTalk tree variable with the
//same name is created/updated
min = stats.min;
max = stats.max;
return stats.N;
}
40
Language Fundamentals
2. From the Origin drop-down menus, select File: New and select Function from the list of
41
LabTalk Scripting Guide
From there, in the Function tab of the Plot Details dialog that opens, enter the function definition,
such as, F1(x) = 5*sin(x)+1 and press OK. The function will be plotted in the graph.
You may define another function by clicking on the New Function button in the graph and adding
another function in Plot Details. Press OK, and the new function plot will be added to the graph.
Repeat if more functions are desired.
file. Using @glob=1, your function becomes available any time the project is opened (see this
example, below).
The scope of a function can be expanded for general use any time that Origin runs by defining
the function using @glob=1, saving the function to an .ogs file in the User Files Folder (UFF),
and calling the .ogs file from the [Startup] section of Origin.ini (also in the UFF), as discussed
here.
42
Language Fundamentals
dGeoMean(col(1))=;
[section1]
// the function can be called in this section too
dGeoMean(col(1))=;
If the function is defined in a section of a *.ogs file without @glob=1, then it can only be called in its
own section.
[Main]
function double dGeoMean(dataset ds)
{
double dG = ds[1];
for(int ii = 2 ; ii <= ds.GetSize() ; ii++)
dG *= ds[ii]; // All values in dataset multiplied together
return exp(ln(dG)/ds.GetSize());
}
// can call the function in [main] section
dGeoMean(col(1))=;
[section1]
// the function can NOT be called in this section
dGeoMean(col(1))=; // an error: Unknown function
If the function is defined in a block without @glob=1, it can not be called outside this block.
[Main]
{ // define the function between braces
function double dGeoMean(dataset ds)
{
double dG = ds[1];
for(int ii = 2 ; ii <= ds.GetSize() ; ii++)
dG *= ds[ii]; // All values in dataset multiplied together
return exp(ln(dG)/ds.GetSize());
}
}
// can Not call the function outside the braces
dGeoMean(col(1))=; // an error: Unknown function
Builder.
2. Expand the Project branch on the left panel tree and double-click to open the
@glob=1;
43
LabTalk Scripting Guide
double y = 10*exp(-(x-x0)^2/4);
return y;
5. In Origin, save the Project to a desired folder location. The OGS file is saved
with the Project, so the user-defined function is available for use in the Project.
6. Open the just saved project again. This will trigger the [AfterOpenDoc] section
8. In the Function tab of Plot Details dialog that opens, enter the function
definition:
F1(x) = myPeak(x, 3)
9. Click on the New Function button in the graph and add another function in Plot
F2(x) = myPeak(x, 4)
11. Now save the Project again and re-open it. The two function plots will still be
available, as they refer to the user-defined function saved with the Project.
12. You can assure yourself that the above really works by first exiting Origin,
reopening Origin, and running the project again, checking that the myPeak
44
Language Fundamentals
These pages contain information on implementing advanced features of the LabTalk scripting
language. Some of the concepts and features in this section are unique to Origin.
Range Notation
Substitution Notation
LabTalk Objects
Origin Objects
String registers
X-Functions Introduction
Similar to other data types, you can declare a Range variable using the following syntax:
range [-option] RangeName = RangeString
The left-hand side of the range assignment is uniform for all types of range assignments. Note that
the square brackets indicate that the option switch is an optional parameter and for different data type
the available option switches are different, please view the Types of Range Data section for details.
Range names follow Origin variable naming rules; please note that system variable names should be
avoided.
45
LabTalk Scripting Guide
The right-hand side of the range assignment, RangeString, changes depending on what type of
object the range points to. Individual Range Strings are defined in the sections below on Types of
Range Data.
worksheet
page
graph layer
loose dataset
Once assigned, the range will represent that object so that you can access the object properties and
methods using the range variable.
range rA = [Book1]Sheet1!Col(A);
rA.name$=;
rA.lname$=;
rA.unit$=;
rA.index=;
rA.nRows=;
To determine which object properties and methods are accessible, open the Script Window and type
the following:
rangeVariable.=;
... where rangeVariable is the name of your range variable.
A range may consist of some subset or some combination of standard Origin Objects. Examples
include:
column subrange
block of cells
XY range
XYZ range
composite range
Worksheet Data
46
Language Fundamentals
[WorkBookName]SheetNameOrIndex!ColumnNameOrIndex[CellIndex]
Note: The WorkBookName andSheetName above used their corresponding Short Name since
Short Name is the default programming name. To use Long Name in range notation for workbook or
worksheet, you have to put Long Name in double quotes such as ["MyBook"]"MySheet"!; whereas
ColumnName can be either the Long Name or the Short Name of the column.
In any RangeString, a span of continuous sheets, columns, or rows can be specified by providing
pairs of sheet, column, or row indices (respectively), separated by a colon, as in index1:index2. The
keyword end can replace index2 to indicate that Origin should pick up all of the indicated objects. For
example:
range rs = [Book1]4:end! // Get sheets 4 through last
range rd = [Book2]Sheet3!5:10; // Get columns 5 through 10
range rr = ["MyBook"]Sheet1!A; // Get column A in sheet 1 with workbook Long
Name
// as MyBook
In the case of rows the indices must be surrounded by square brackets, so a full range assignment
statement for several rows of a worksheet column looks like:
range rc1 = [Book1]Sheet2!Col(3)[10:end]; // Get rows 10 through last
range rc2 = [Book1]Sheet2!Col(3)[10:20]; // Get rows 10 through 20
The old way of accessing cell contents, via the Cell function is still supported.
If you wish to access column label rows using range, please see Accessing Metadata and the
Column Label Row Reference Table.
Column
When declaring a range variable for a column on the active worksheet, the book and sheet part can
be dropped, such as:
range rc = Col(3)
You can further simplify the notation, as long as the actual column can be identified, as shown below:
range aa=1; // col(1) of the active worksheet
range bb=B; // col(B) of the active worksheet
range cc="Test A"; // col with Long Name ("Test A"), active worksheet
Note: the quotation mark used in the range string expression always refers to long name, even
though the long name is identical to an expression of worksheet (e.g. 1!), the range string "1!" refers
to the column with long name 1!. This behavior could be turned off by using the system variable
@RPQ, for details please refer to this table.
Multiple range variables can be declared on the same line, separated by comma. The above example
could also have been written as:
range aa = 1, bb = B, cc = "Test A";
Or if you need to refer to a different book sheet, and all in the same sheet, then the book sheet
portion can be combined as follows:
range ["MyBook"]Sheet3 aa=1, bb=B, cc="Test A"; //Book Long Name is MyBook
Because Origin does not force a column's Long Name to be unique (i.e., multiple columns in a
worksheet can have the same Long Name), the Short Name and Long Name may be specified
together to be more precise:
range dd = D"Test 4"; // Assign Col(D), Long Name 'Test 4', to a range
Once you have a column range, use it to access and change the parameters of a column:
range rColumn = [Book1]1!2; // Range is a Column
rColumn.digitMode = 1; // Use Set Decimal Places for display
rColumn.digits = 2; // Use 2 decimal places
Or perform computations:
47
LabTalk Scripting Guide
When performing arithmetic on data in different sheets, you need to use range
variables. Direct references to range strings are not yet supported. For example, the
script Sheet3!col(1) = Sheet1!col(1) + Sheet2!col(1); will not work! If you really need
to write in a single line without having to declare range variables, then use Dataset
Substitution.
Besides a single column of data, a range can be used to access any portion of a page object:
Use a range variable to access an entire workbook:
// 'rPage' points to the workbook named 'Book1'
range rPage = [Book1];
Column Subrange
Block of Cells
Use a range to access a single cell or block of cells (may span many rows and columns) as in:
range aa = 1[2]; // cell(2,1), row2 of col(1)
range bb = 1[1]:3[10]; // cell(1,1) to cell(10,3)
48
Language Fundamentals
Note: A range variable representing a block of cells can be used as an X-Function argument only,
direct calculations are not supported.
Option Switch -v
Matrix Data
49
LabTalk Scripting Guide
Access the cell contents of a matrix range using the notation RangeName[row, col]. For example:
range mm=[MBook1]1!1;
mm[2,3]=10;
If the matrix contains complex numbers, the string representing the complex number can be
accessed as below:
string str$;
str$ = mm[3,4]$;
Graph Data
For graph windows, you can use range -w and range -wx, range -wy, range -wz options to get the
worksheet column range of a plotted dataset.
range -w always gets the worksheet range of the most dependent variable - which is the Y value for
2D plots and the Z value or matrix object for 3D plots. And since Origin 9.0 SR0, multiple ranges are
supported for range -w.
range -wx, range -wy, and range -wz will get the worksheet range of the corresponding X, Y and Z
values, respectively.
range -wx, range -wz Require Version: 9.0 SR0
// Make a graph window the active window ...
// Get the worksheet range of the Y values of first dataplot:
range -w rW = 1;
// Get the current selection (%C); will resolve data between markers.
range -w rC = %C;
Note that in the script above, rW = [Book1]Sheet1!B while rG = [Graph1]1!1.
You can use the Data Selector tool to select one or more ranges on a graph and to refer to them from
LabTalk. For a single selected range, you can use the MKS1, MKS2 system variables. Starting with
version 8.0 SR6, a new X-Function, get_plot_sel, has been added to get the selected ranges into a
string that you can then parse. The following example shows how to select each range on the current
graph:
string strRange;
get_plot_sel str:=strRange;
50
Language Fundamentals
StringArray sa;
sa.Append(strRange$,"|"); // Tokenize it
int nNumRanges = sa.GetSize();
if(nNumRanges == 0)
{
type "there is nothing selected";
return;
}
type "Total of $(nNumRanges) ranges selected for %C";
for(int ii = 1; ii <= nNumRanges; ii++)
{
range -w xy = sa.GetAt(ii)$;
string strWks$ = "Temp$(ii)";
create %(strWks$) -wdn 10 aa bb;
range fitxy = [??]!(%(strWks$)_aa, %(strWks$)_bb);
fitlr iy:=xy oy:=fitxy;
plotxy fitxy p:=200 o:=<active> c:=color(red) rescale:=0 legend:=0;
type "%(xy) fit linear gives slope=$(fitlr.b)";
}
// clear all the data markers when done
mark -r;
Additional documentation is available for the the Create (Command) (for creating loose datasets), the
[??] range notation (for creating a range from a loose dataset), the fitlr X-Function, and the
StringArray (Object) (specifically, the Append method, which was introduced in Origin 8.0 SR6).
When working with an XY range, you can specify a subrange using the X values. The syntax is as
follows:
1. From Worksheet
[WorkBookName]SheetNameOrIndex!YColumnNameOrIndex[xX1:X2]
Example:
// Using Columns 1 and 2 for X and Y, specify subrange from x=0.15 to 0.2
range rxy = (1, 2)[x0.15:0.2];
1. From Graph
[GraphWindowName]LayerNameOrIndex!DataPlot[xX1:X2]
Example:
// XY subrange of the 2nd curve on Graph1, Layer1
range rxy2 = [Graph1]Layer1!2[x5:20];
The following example uses the plotxy X-Function to plot a graph, and then the smooth X-Function to
smooth a subrange of the data.
// Import data into a new book
newbook;
fname$ = system.path.program$ + "\Samples\Signal Processing\EMG
Recording.dat";
impasc;
51
LabTalk Scripting Guide
Loose Dataset
Loose Datasets are similar to columns in a worksheet but they don't have the overhead of the book-
sheet-column organization. They are typically created with the create command, or automatically
created from an assignment statement without Dataset declaration.
The RangeString for a loose dataset is:
[??]!LooseDatasetName
Assignment can be performed using the syntax:
range xx = [??]!tmpdata_a; // Loose dataset 'tmpdata_a'
To show how this works, we use the plotxy X-Function to plot a graph of a loose dataset.
// Create 2 loose datasets
create tmpdata -wd 50 a b;
tmpdata_a=data(50,1,-1);
tmpdata_b=normal(50);
// Declare the range and explicitly point to the loose dataset
range aa=[??]!(tmpdata_a, tmpdata_b);
// Make a scatter graph with it:
plotxy aa;
Loose datasets belong to a project, so they are different from a Dataset variable,
which is declared, and has either session or local scope. Dataset variables are also
internally loose datasets but they are limited to use in calculations only; they cannot be
used in making plots, for example.
Return the size of the range. This method works for a dataset range,
such as column, matrix object, graph plot, block of cells, loose
range.getSize()
dataset, etc. Note that, for a block of cells, it only returns the size of
the first sub column specified in the range declaration.
Set the size of the range. This method works for a dataset range,
such as column, matrix object, graph plot, block of cells, loose
range.setSize()
dataset, etc. If the range is block of cells, it only set the size for the
first sub column specified in the range declaration.
52
Language Fundamentals
name of the page, you need the $ sign after the method, such as
"rng.getPage()$ = ".
A column range can be used to manipulate data directly. One major advantage of using a range
rather than the direct column name, is that you do not need to be concerned with which page or layer
is active.
For example:
// Declare two range variables, v1 and v2:
range [Book1]Sheet1 r1=Col(A), r2=Col(B);
53
LabTalk Scripting Guide
Sometimes it is beneficial to be able to create a new range in an automated way, at runtime, using a
variable column number, or the name of another range variable.
The wcol() function is used to allow runtime resolution of actual column index, as in
int nn = 2;
range aa=wcol(2*nn +1);
The following lines of script demonstrate how to create one range based on another using the %( )
substitution notation and wks (object) methods. When the %( ) substitution is used on a range
variable, it always resolves it to a [Book]Sheet! string, regardless of the type:
range rwks = sheet3!;
range r1= %(rwks)col(a);
in this case, the new range r1 will resolve to Sheet3!Col(A).
This method of constructing new range based on existing range is very useful because it allows code
centralization to first declare a worksheet range and then to use it to declare column ranges. Lets
now use the rwks variable to add a column to Sheet 3:
rwks.addcol();
And now define another range that resolves to the last (rightmost) column of range rwks; that is, it
will point to the newly made column:
range r2 = %(rwks)wcol( %(rwks)wks.ncols );
With the range assignments in place it is easy to perform calculations and assignments, such as:
r2=r1/10;
which divides the data in range r1 by 10 and places the result in the column associated with range r2.
X-Function Argument
Many X-functions use ranges as arguments. For example, the stats X-Function takes a vector as
input and calculates descriptive statistics on the specified range. So you can type:
stats [Book1]Sheet2!(1:end); // stats on the second sheet of book1
stats Col(2); // stats on column 2 of active worksheet
54
Language Fundamentals
Some X-Functions use a special type of range called XYRange, which is essentially a composite
range containing X and Y as well as error bar ranges.
The general syntax for an XYRange is
(rangeX, rangeY)
but you can also skip the rangeX portion and use the standard range notation to specify an XYRange,
in which case the default X data is assumed.
The following two notations are identical for XYRange,
(, rangeY)
rangeY
For example, the integ1 X-Function takes both input and output XYRange,
// integrate col(1) as X and col(2) as Y,
// and put integral curve into columns 3 as X and 4 as Y
integ1 iy:=(1,2) oy:=(3,4);
Use the list LabTalk command to print a list of names and their defined bodies of all session
variables including the range variables. For example:
list a; // List all session variables
If you issue this command in the Command Window, it prints a list such as:
Session:
1 MYRANGE [book1]sheet1!col(b)
2 MYSTR "abc"
3 PI 3.1415926535898
As of Origin 8.1, more switches have been added (given below) to list particular session variables:
Option What Gets Listed Option What Gets Listed
afc Local Function Full Content (session) afp Local Function Prototype (session)
To delete a range variable, use the del LabTalk command with the -ra switch. For example:
range aa=1; // aa = Col(1) of the active worksheet
range ab=2; // ab = Col(2) of the active worksheet
range ac=3; // ac = Col(3) of the active worksheet
55
LabTalk Scripting Guide
Each Origin Object has a short name, long name, and universal identifier (UID). You can convert
between range variables and their UIDs as well as obtain the names of pages and layers using the
functions range2uid, uid2name, and uid2range. See LabTalk Objects for examples of use.
For instance, the fitpoly X-Function takes an XY range for both input and output:
// Fit a 2nd order polynomial to the XY data in columns 1 and 2;
// Put the coefficients into column 3 and the XY fit data in cols 4 and 5:
fitpoly iy:=(1,2) polyorder:=2 coef:=3 oy:=(4,5);
There are two special characters '?' and '#' introduced in (8.0 SR3) for range as an X-Function
argument. '?' indicates that the range is forced to use worksheet designation, and will fail if the range
designation does not satisfy the requirement. '#' means that the range ignores designations and uses
row number as the X designation. However, if the Y column has even sampling information, that
sampling information will be used to provide X.
For example:
plotxy (?, 5); // if col(5) happens to be X column call fails
plotxy (#, 3); // plot col(3) as Y and use row number as X
These notations are particularly handy in the plotxy X-Function, as demonstrated here:
// Plot all columns in worksheet using their column designations:
plotxy (?,1:end);
56
Language Fundamentals
Many X-Functions have an output range that can be modified with tags, including template, name,
and index. Here is an example that can be used by the Discrete Frequency X-Function, discfreqs
discfreqs irng:=1 freq:=1 rd:="[Result]<new template:=table.otw index:=3>";
The output is directed to a Workbook named Result by loading a template named TABLE.OTW as
the third sheet in the Result book.
Support of tag notation depends on the particular X-Function, so verify tag notation is supported
before including in production code.
Composite Range
A Composite Range is a range consisting of multiple subranges. You can construct composite ranges
using the following syntax:
// Basic combination of three ranges:
(range1, range2, range3)
// Activate workbook again and add more sheets and fill them with data.
// Plot A(X)B(Y) from all sheets between row2 and row10:
plotxy (1:end)!(1,2)[2:10];
Note: There exists an inherent ambiguity between a composite range, composed of ranges r1 and r2
as in (r1,r2), and an XY range composed of columns named r1 and r2, i.e., (r1,r2). Therefore, it is
important that one keep in mind what type of object is assigned to a given range variable!
3.3.3.1 Introduction
When a script is executed, it is sent to the LabTalk interpreter. Among other tasks, the interpreter
searches for special substitution notations, which are identified by their initial characters, % or $.
When a substitution notation is found, the interpreter replaces the original string with another string,
as described in the following section. The value of the substituted string is unknown until the
statement is actually executed. Thus, this procedure is called a run-time string substitution.
57
LabTalk Scripting Guide
%( ) Substitution, a powerful notation to resolve %(str$), %(range), worksheet info and column
$( ) Substitution, where $(expression) resolves the numeric expression and formats the result
as a string
3.3.3.2 %A - %Z
Using a string register is the simplest form of substitution. String registers are substituted by their
contents during script execution, for example
FDLOG.Open(A); // put file name into %A from dialog
%B=FDLOG.path$; // file path put into %B
doc -open %B%A; // %B%A forms the full path file name
String registers are used more often in older scripts, before the introduction of string variables (Origin
8), which allows for more reliable codes. To resolve string variables, %( ) substitution is used, and is
discussed in the next section.
3.3.3.3 %( ) Substitution
While LabTalk commands often accept numeric expressions as arguments, none accept a string
expression. So if a string is needed as an argument, you have to pass in a string variable or a string
expression using the %( ) substitution to resolve run-time values. The simplest form of a string
expression is a single string variable, like in the example below:
string str$ = "Book2";
win -o %(str$) {wks.ncols=;}
Keyword Substitution
The %( ) substitution notation is also used to insert non-printing characters (also called control
characters), such as tabs or carriage returns into strings. Use LabTalk keywords to access these non-
printing characters. For example,
// Insert a carriage-return, line-feed (CRLF) into a string:
string ss$ = "Hello%(CRLF)Goodbye";
ss$=; // ANS: 'Hello', 'Goodbye' printed on separate lines
// Can be typed directly
type ss$;
// But use %() substitution when mixed with literals
ty I say %(ss$) you say;
The following notation allows you to access worksheet cells as a string as well as to get the column
dataset name from any workbook sheet. Before Origin 8, each book had only one sheet so you could
refer to its content with the book name only. Since Origin 8 supports multiple worksheets, we
recommend that you use [workbookname]sheetname to refer to a specific sheet, unless you are
58
Language Fundamentals
Before 8.1, you must use column and row index and numeric cell will always return full precision.
Origin 8.1 has added support for column to allow both index and name, and row will also support
Label Row Characters such as L for longname.
There is also an optional format argument that you can use to further specify numeric cell format
when converting to string. Assuming Book2, sheet3 col(Signal)[3] has a numeric value of
12.3456789, but only 2 decimal places are displayed (this setting needs be done in the Column
Properties dialog).
//format string W to use current column format
//Should return 12.34
type "Col(Signal)[3] displayed value is %([Book2]Sheet3,Signal,3,W)";
//full precision if format not specified
A=%([Book2]Sheet3,Signal,3);
A=;// shows 12.3456789
//Or use other format notations
type "Showing 3 decimal places:%([Book2]Sheet3,Signal,3,.3)";
Another syntax can be used to maintain the cell format of the data, for customizations made either in
the Format Cells dialog or the Column Properties dialog:
%([workbookName]sheetName, @WL, column[row], W)
A similar example is shown below:
//Or use another expression with @WL option to keep the display format
type "Col(Signal)[3] displayed value is %([Book2]Sheet3, @WL, Signal[3], W)";
//full precision if format not specified
B=%([Book2]Sheet3,@WL, Signal[3]);
B=;// shows 12.3456789
Note: The format character W is introduced in 9.1 SR0 to replace the usage of C in previous
versions. However, Origin maintains support for the use of %([workbookName]sheetName,
column, row,C) to return the value of the current column format.
To return a dataset name, use the following syntax:
Older notation for active sheet of named book
%(workbookName, column)
New Origin 8 book sheet notation
%([workbookName]sheetName, column)
You can also use index
59
LabTalk Scripting Guide
%([workbookName]SheetIndex, column)
where column must be an index prior to Origin 8.1 which added support for column name.
For example:
%A = %(%H, 2); // Column 2 of active sheet of active book
type %A;
%B = %([Book1]Sheet3,2); // Column 2 of Book1, Sheet3
type %B;
In the above example, the name of the dataset in column 2 in the active worksheet is substituted for
the expression on the right, and then assigned to %A and %B. In the second case, if the named book
or sheet does not exist, no error occurs but the substitution will be invalid.
Note: You can use parentheses to force assignment to be performed on the dataset whose name is
contained in a string register variable instead of performing the assignment on the string register
variable itself.
%A = %(Book1,2); // Get column 2 dataset name
type %A; // Types the name of the dataset
(%A) = %(Book1,1); // Copy column 1 data to column 2
The ability to get a dataset name from any book or sheet (Dataset Substitution) can be very useful in
doing calculations involving columns in different sheets, like:
// Sum col(1) from sheet2 and 3 and place the result into col(1) of the
active sheet
col(1)=%([%H]sheet2, 1) + %([%H]sheet3, 1);
Similar to worksheet column and cell access with substitution notation, the @ Substitution (worksheet
info substitution) make uses of the @ character to differentiate from a column index or name in the
2nd argument to specify various options to provide access to worksheet info and meta data.
The following syntax can be used for worksheet information substitution and is still supported for the
active sheet:
%(workbookName, @option, columnNumber)
It is recommended that you use the newer notation introduced in Origin 8:
%([workbookName]worksheetName, @option, columnNumber)
Here, option can be one of the following:
Option Return Value
@CS Returns the column index of the first selected column to the right of (and including) the
60
Language Fundamentals
Use with %H to return the Project Explorer (PE) path of the active window (%(%H,
@P
@P)).
Returns the offset from the left-most selected Y column to the columnNumber column
@OY
in the current selection.
Returns the offset from the left-most selected Y column to the columnNumber Y
@OYX
column counting on Y columns in the current selection.
Returns the offset from the left-most selected Y column to the columnNumber X
@OYY
column counting on X columns in the current selection.
Returns the index number of the worksheet's first X column. Columns are enumerated
@X
from left to right, starting from 1. Use the syntax: %(worksheetName, @X);
Returns the column short name of the worksheet's first X column. Use the syntax:
@Xn
%(worksheetName, @Xn);
Returns the offset from the left-most selected column to the columnNumber column in
@Y
the current selection.
Returns the column number of the first Y column to the left. Returns columnNumber if
@Y- the column is a Y column, or returns 0 when the Y column doesn't exist. Use the
syntax: %(worksheetName, @Y-, ColumnNumber);
61
LabTalk Scripting Guide
Returns the column number of the first Y column to the right. Returns columnNumber
@Y+ if the column is a Y column, or returns 0 when the Y column doesn't exist. Use the
syntax: %(worksheetName, @Y+, ColumnNumber);
Returns the number of the first selected Y column to the right of (and including) the
@YS
columnNumber column.
The @W variables access metadata stored within Origin workbooks, worksheets, and columns, as
well as information stored about imported files.
Use a similar syntax as above, replacing column number with variable or node information:
%([workbookName]worksheetName!columnName, @option, varOrNodeName)
Option Return Value
Returns the information in varOrNodeName for the nth imported file. The variable can
@WFn
be seen in the workbook Organizer.
Examples of @ Substitution
This script returns the column name of the first column in the current selection range (for information
on the selc1 numeric system variable, see System Variables):
%N = %(%H, @col, selc1); %N =;
This script returns the Project Explorer path of the active window:
%P = %(%H, @P); %P=;
The following line returns the active page's long name to a string variable:
string PageName$ = %(%H, @PL);
The script below returns the column type for the fourth column in Book 2, Sheet 3:
string colType$ = %([Book2]Sheet3, @T, 4);
colType$=;
62
Language Fundamentals
An import filter can create a tree structure of information about the imported file that gets stored with
the workbook. Here, for a multifile import, we return the number of points in the 3rd dataset imported
into the current book:
%z=%(%H,@WF3,variables.header.noofpoints);
%z=
If the currently active worksheet window has six columns (XYYYYY) and columns 2, 4, and 5 are
selected, then the following script shows the number of the first selected Y column to the right of (and
including) the column whose index is equal to columnNumber (the third argument):
loop(ii,1,6)
{
type -l %(%H, @YS, ii),;
}
type;
This outputs:
2,2,4,4,5,0,
Graph legends and axis titles also employ the %( ) substitution notation. The first argument must be
an integer to differentiate it from other %( ) notations, where the first argument is a worksheet
specifier. The legend and axis title substitution syntax is:
%(PlotIndex[, @option])
where PlotIndex is the index of the data plot in the current layer or a questions mark ?. The variable
PlotIndex might be followed by more options, such as a plot designation character (X, Y or Z)
associated with the data plot; when not specified this is assumed to be Y. The @option parameter is
an optional argument that controls the legend contents. For example:
// In the legend of the current graph layer ...
// display the Long Name for the first dependent dataset.
legend.text$ = %(1Y, @LL)
You can refer to the legend substitution notation page for further information and the text label
options page for a complete list of @options.
Note: This style of legend modification is limited in that it only changes a single legend entry, but the
syntax is good to understand, as it can be used in the Plot Details dialog.
3.3.3.4 $( ) Substitution
63
LabTalk Scripting Guide
The $() notation is used for numeric to string conversion. This notation evaluates the given
expression at run-time, converts the result to a numeric string, and then substitutes the string for
itself.
The notation has the following form:
$(expression [, format])
where expression can be any mathematical expression, but typically a single number or
variable(dataset and data range), and format can be either an Origin output format or a C-language
format.
If expression is a dataset or range variable, it returns a value list separated by space. (Minimum
Version: 9.1 SR0)
For example:
//Define a dataset
dataset ds1 = {1, 3, 5, 7};
//Output the result of substitution notation
type $(ds1);//ANS:1 3 5 7;
type $(ds1, *2);//ANS: 1.0 3.0 5.0 7.0
Default Format
The square brackets indicate that format is an optional argument for the $() substitution notation. If
format is excluded Origin will carry expression to the number of decimal digits or significant digits
specified by the @SD system variable (which default value is 14). For example:
double aa = 3.14159265358979323846;
type $(aa); // ANS: 3.1415926535898
Origin Formats
64
Language Fundamentals
Display in custom date format, using these date and time format
D<format>
specifiers
Display date in format n from the Display drop down list of the
Dn
Column Properties dialog box (indexed from "0")
Display in custom time format, using these date and time format
T<format>
specifiers
Display time in format n from the Display drop down list of the
Tn
Column Properties dialog box (indexed from "0")
yy = 1.10001;
type "yy = $(yy, *4)"; // ANS: 1.100
type "yy = $(yy, *4*)"; // ANS: 1.1
zz = 203465987;
type "zz = $(zz, E*3)"; // ANS: 203M
type "zz = $(zz, S*3)"; // ANS: 2.03E+08
65
LabTalk Scripting Guide
C-Language Formats
The format portion of the $() notation also supports C-language formatting statements.
Option Un/Signed Output Input Range
f, e, E, g, +/-1e290 -- +/-1e-
SIGNED Decimal, scientific, decimal-or-scientific
G 290
double nn = 1.23456e5;
type "Values: $(nn, %9.4f), $(nn, %9.4E), $(nn, %g)";
// ANS: 123456.0000, 1.2346E+005, 123456
double nn = 1.23456e6;
type "Values: $(nn, %9.4f), $(nn, %9.4E), $(nn, %g)";
// ANS: 123456.0000, 1.2346E+006, 1.23456e+006
double nn = 65551;
type "Values: $(nn, %o), $(nn, %u), $(nn, %X)";
// ANS: 200017, 65551, 1000F
Origin supports the use of formats E and S along with C-language format specifiers. For example:
xx = 1e6;
type "xx = $(xx, E%4.2f)"; // ANS: 1.00M
The command parsing for the type command (and others) looks for the - character as an option
switch indicator. If you assign a negative value to the variable K and try to use the type command to
express that value, you must protect the - by enclosing the substitution in quotes or parentheses. For
example:
K = -5;
type "$(K)"; // This works
type ($(K)); // as does this
type $(K); // but this fails since type command has no -5 option
66
Language Fundamentals
Note that in assignment statements, the $() notation is substitution-processed and resolved to a value
regardless of which side of the assignment operator it is located.
This script creates a variable A with the value 2.
A = 2;
Then we can create a variable A2 with the value 3 with this notation:
A$(A) = 3;
You can verify it by entering A$(A) = or A2 = in the Script window.
3.3.4.1 Properties
A property either sets or returns a number or a text string associated with an object with the following
syntax:
objName.property (For numeric properties)
objName.property$ (For text properties)
Where objName is the name of the object; property is a valid property for the type of object. When
accessing text objects, you should add the $ symbol after property.
For example, you can set object properties in the following way:
// Set the number of columns on the active worksheet to 10
wks.ncols = 10;
// Rename the active worksheet 'MySheet'
67
LabTalk Scripting Guide
wks.name$ = MySheet;
Or you can get property values:
pn$ = page.name$; // Get that active page name
layer.x.from = ; // Get and display the start value of the x-axis
3.3.4.2 Methods
Methods are a form of immediate command. When executed, they carry out a function related to the
object and return a value. Object methods use the following syntax:
objName.method(arguments)
Where objName is the name of the object; method is a valid method for the type of object; and
arguments determine how the method functions. Some arguments are optional and some methods
do not require any arguments. However, the parentheses "()" must be included in every object
method statement, even if their contents are empty.
For example, the following code uses the section method of the run object to call the Main section
within a script named computeCircle, and passes it three arguments:
double RR = 4.5;
string PA$ = "Perimeter and Area";
run.section(computeCircle, Main, PA$ 3.14 R);
str$ = uid2name(nVal)$
str$ = uid2range(nVal)$
68
Language Fundamentals
Given a range variable, you can get its corresponding Page and Layer UID. The following code
shows how to make a hidden plot from XY data in the current sheet and to obtain the hidden plot's
graph page name:
plotxy (1,2) hide:=1; // plot A(x)B(y) to a new hidden plot
range aa=plotxy.ogl$;
int uid=aa.GetPage();
string str$=uid2Name(uid)$;
type "Resulting graph name is %(str$)";
You can also get a data plot's related workbook and worksheet as range variables. The following
code (requires Origin 8 SR2) shows how to get the Active plot (%C) as a column range and then
retrieve from it the corresponding worksheet and book variables allowing complete access to the plot
data:
// col range for active plot, -w switch default to get the Y column
range -w aa=%C;
// wks range for the sheet the column belongs to
range ss = uid2range(aa.GetLayer())$;
// show sheet name
ss.name$=;
// book range from that col
range bb = uid2range(aa.GetPage())$;
// show book name
bb.name$=;
There is also a simpler way to directly use the range string return from GetLayer and GetPage in
string form:
// col range for active plot, -w switch default to get the Y column
range -w aa=%C;
// sheet range string for the sheet the column belongs to
range ss = aa.GetLayer()$;
// show sheet name
ss.name$=;
// book range string from that col
range bb = aa.GetPage()$;
// show book name
bb.name$=;
When you create a range mapped to a page, the range variable has the properties of a PAGE
(Object).
When you create a range mapped to a graph layer, the range variable has the properties of a LAYER
(Object).
When you create a range mapped to a workbook layer (a worksheet or matrix sheet), the range
variable has the properties of a WKS (Object).
69
LabTalk Scripting Guide
2. Worksheet Object
3. Column Object
4. Layer Object
5. Matrix Object
6. Dataset Object
7. Graphic Object
Except loose datasets, Origin objects can be organized into three hierarchies:
Workbook -> Worksheet -> Column
Matrix Book -> Matrix Sheet -> Matrix Object
Graph Window -> Layer -> Dataplot
In the sections that follow, tables list object methods and examples demonstrate the use of these
objects in script.
String registers are of global scope; this means that they can be changed by any script
at any time. Sometimes this is useful, other times it is dangerous, as one script could
change the value in a string register that is being used by another script with
erroneous and confusing results.
Some string registers are reserved for use as system variables, and attempting to
assign values to them could result in errors in your script. They are grouped in the
ranges %C--%I, and %X--%Z, or are preceded by a %@ (e.g. %@A = Apps root
folder). Consult the tables below.
70
Language Fundamentals
String registers hold up to 260 characters (%Z holds up to 6290). String register names are
comprised of a %-character followed by a single alphabetic character (a letter from A to Z); for this
reason, string registers are also known as % variables. Of the 26 possible string registers, the
following are reserved as system variables that have a special meaning, and they should not be
reassigned in your scripts. It is often helpful, however, to have access to (or operate on) the values
they store.
%
Description
Variable
The full path name to the User Files folder, where the user .INI files as well as
other user-customizable files are located. %Y can be different for each user
depending on the location they selected when Origin was started for the first time.
Prior to Origin 7.5, the path to the various user .INI files was the same as it was to
the Origin .EXE. Beginning with Origin 7.5, we added multi-user-on-single-
%Y workstation support by creating a separate "User Files" folder.
To get the Origin .EXE path(program path), use the following LabTalk statement:
%a = system.path.program$
The following extra read-only system string registers comprised of %@-characters followed by a
single alphabetic character are added from Origin 2016 SR2. ;
%@
Description
Variable
%@H The book name that contains the active embedded graph.
71
LabTalk Scripting Guide
User AppData Root folder. This folder stores the xml file that lists installed apps
%@Y
and their version number.
String registers containing system variables can be used anywhere a name can be used, as in the
following example:
// Deletes the current active dataset:
del %C;
By using parentheses, the string variable on the left of the assignment operator can be expressed
before the assignment is made. For example, enter the following assignment statement in the Script
window:
%B = Book1_A
This statement assigns the string register %B the value Book1_A. If Book1_A is a dataset name,
then entering the following assignment statement in the Script window:
(%B) = 2*%B
results in the dataset being multiplied by 2. String register %B, however, still contains the string
Book1_A.
String Comparison
When comparing string registers, use the "equal to" operator (==).
If string registers are surrounded by quotation marks (as in, "%a"), Origin literally compares the
aaa = 4;
bbb = 4;
72
Language Fundamentals
%A = aaa;
%B = bbb;
if ("%A" == "%B")
type "YES";
else
type "NO";
The result will be NO, because in this case aaa != bbb.
If string registers are not surrounded by quotation marks (as in, %a), Origin compares the
aaa = 4;
bbb = 4;
%A = aaa;
%B = bbb;
if (%A == %B)
type "YES";
else
type "NO"
The result will be YES, because in this case the values of the strings (rather than the characters) are
compared, and aaa == bbb == 4.
Substring Notation
Substring notation returns the specified portion of a string. The general form of this notation is:
%[string, argument];
where string contains the string itself, and argument specifies which portion of the string to return.
For the examples that follow, enter this assignment statement in the Script window:
%A = "Results from Data2_Test"
The following examples illustrate the use of argument in substring notation:
To do this: Enter this script: Return value:
Return the #n token, counting from the left. %B = %[%A, #2]; %B = from
73
LabTalk Scripting Guide
Note:
For example, to set %A equal to 5 and find the length of %A, type the following in the Script window
and press Enter:
%A = " 5 ";
ii = %[%A];
ii = ;
Origin returns: ii = 3.
A Note on Tokens
A token can be a word surrounded by white space (spaces or TABS), or a group of words enclosed in
any kind of brackets. For example, if:
%A = These (are all) "different tokens"
then entering the following in the Script window:
Scripts Returns
74
Language Fundamentals
2. OGS Files
3. X-Functions
75
4 Calling X-Functions and Origin C Functions
This chapter covers how to call X-Functions and Origin C functions from LabTalk.
X-Functions
Origin C Functions
4.2 X-Functions
4.2.1 X-Functions
X-Functions are a primary tool for executing tasks and tapping into Origin features from your LabTalk
scripts. The following sections outline the details that will help you recognize, understand, and utilize
X-Functions in LabTalk.
X-Functions Overview
4.2.2.1 Syntax
77
LabTalk Scripting Guide
You can recognize X-Functions in script examples from their unique syntax:
xFunctionName input:=<range> argument:=<name/value> output:=<range> -switch;
General Notes:
X-Functions can have multiple inputs, outputs, and arguments.
X-Functions can be called with any subset of their possible argument list supplied.
If not supplied a value, each required argument has a default value that is used.
Expected argument order can be found in the help file for each individual X-Function or from
If the arguments are supplied in the order specified by Origin, there is no need to type out the
argument names.
If the argument names are explicitly typed, arguments can be supplied in any order.
You can mix handling of arguments as long as omitted arguments come first in the specified
The argument name can be shortened by trimming characters from the end of the argument
The following examples use the fitpoly X-Function to illustrate these points.
4.2.2.2 Examples
The fitpoly X-Function has the following specific syntax, giving the order in which Origin expects the
arguments:
fitpoly iy:=(inputX,inputY) polyorder:=n fixint:=(0=No/1=Yes) intercept:=value coef:=columnNumber
oy:=(outputX,outputY) N:=numberOfPoints;
If given in the specified order, the X-Function call,
//Polynomial fit on XY data (X-column 1, Y-column 2),
//Polynomial order = 4
// Not fix intercept value, Initial intercept Value is 0,
//Output Coef in column 3,
//Output X value in column 4, Output Y values in column 5,
//Number of points of output XY =100
fitpoly (1,2) 4 0 0 3 (4,5) 100;
tells Origin to fit a 4th order polynomial with 100 points to the X-Y data in columns 1 and 2 of the
active worksheet, putting the coefficients of the polynomial in column 3, and the X-Y pairs for the fit in
columns 4 and 5 of the active worksheet.
In contrast, the command with all options typed out is a bit longer but performs the same operation:
fitpoly iy:=(1,2) polyorder:=4 coef:=3 oy:=(4,5) N:=100;
In return for typing out the input and output argument names, LabTalk will accept them in any order,
and still yield the expected result:
78
Calling X-Functions and Origin C Functions
79
LabTalk Scripting Guide
Note: The Dialog Theme box and corresponding Generate Script fly-out menu item are not
available from all X-Function dialogs that you open with the -d option (for instance, compare fitpoly -
d with rnormalize -d).
For
graph,
1. (1,2) use
index
2. <new> directly
A
to
combination 3. (1,2:end) indicate
of X, Y, and
XYRange plot
optional Y 4. (<input>,<new>) range
Error Bar
(1,2)
data 5. [book2]sheet3!<new> means
1st and
2nd
plots on
graph
1. (1,2,3)
A 2. <new>
combination
XYZRange
of X, Y, and 3. [book2]sheet3!(1,<new>,<new>)
Z data
A Tree
based
object for a
Hierarchical 1. <new>
Report
Must be 2. [<input>]<new>
ReportTree associated
with a 3. [book2]sheet3
worksheet
range or a
LabTalk
Tree
variable
80
Calling X-Functions and Origin C Functions
A Tree
based
object for a
collection of
vectors
Must be
associated
with a
worksheet
range or a
LabTalk
Tree
variable. 1. <new>
Unlike
ReportTree, 2. [<input>]<new>
ReportData
outputs to a 3. [book2]sheet3
ReportData
regular
worksheet 4. [<input>]<input>!<new>
and thus
can be
used to
append to
the end of
existing
data in a
worksheet.
All the
columns in
a
ReportData
object must
be grouped
together.
To understand these variable types better, please refer to the real examples in the ReportData
Output section below, which have shown some concrete usages.
81
LabTalk Scripting Guide
Many X-Functions generate multiple output vectors in the form of a ReportData object. Typically, a
ReportData object is associated with a worksheet, such as the Fit Curves output from the NLFit X-
Function. Consider, for example, the output from the fft1 X-Function:
// Send ReportData output to Book2, Sheet3.
fft1 rd:=[book2]sheet3!;
// Send ReportData output to a new sheet in Book2.
fft1 rd:=[book2]<new>!;
// Send ReportData output to Column 4 in the active workbook/sheet.
fft1 rd:=[<active>]<active>!Col(4);
// Send ReportData output to a new sheet in the active workbook.
fft1 rd:=[<active>]<new>!;
// Send ReportData output to a tree variable named tr1;
// If 'tr1' does not exist, it will be created.
fft1 rd:=tr1;
Often, you may need the ReportData output only as an intermediate variable and thus may prefer not
to involve the overhead of a worksheet to hold such data temporarily.
One alternative then is to store the datasets that make up the Report Data object using a Tree
variable, which already supports bundling of multiple vectors, including support for additional
attributes for such vectors.
The output range specification for a worksheet is usually in one of the following forms: [Book]Sheet!,
<new>, or <active>. If the output string does not have one of these usual book-sheet specifications,
then the output is automatically considered to be a LabTalk Tree name.
The following is an example featuring the avecurves X-Function. In this example, the resulting
ReportData object is first output to a tree variable, and then one vector from that tree is placed at a
specific column-location within the same sheet that houses the input data. ReportData output typically
defaults to a new sheet.
int nn = 10;
col(1)=data(1,20); //fill some data
loop(i,3,nn){wcol(i)=normal(20);};
range ay=col(2); //for 'avecurves' Y-output
Tree tr; // output Tree
avecurves (1,3:end) rd:=tr;
// Assign tree node (vector) 'aveY' to the range 'ay'.
// Use 'tr.=' to see the tree structure.
ay=tr.Result.aveY;
ay[L]$="Ave Y"; // set its LongName
// Plot the raw data as scatter-plot using the default-X.
plotxy (?,3:end) p:=201;
// Add the data in range 'ay' to the same as line-plot.
plotxy ay o:=<active> p:=200;
If you are happy with simply putting the result from the X-Function into the input sheet as new
columns, then you can also do the following:
avecurves (1,2:5) rd:=[<input>]<input>!<new>;
Or if you would like to specify a particular column of the input sheet in which to put the ReportData
output, you may specify that as well:
avecurves (1,2:5) rd:=[<input>]<input>!Col(3);
Subsequent access to the data is more complicated, as you will need to write additional code to find
these new columns.
82
Calling X-Functions and Origin C Functions
Realize that output of the ReportData type will contain different amounts (columns) of
data depending on the specific X-Function being used. If you are sending the results
to an existing sheet, be careful not to overwrite existing data with the ReportData
columns that are generated.
-h -help Prints the contents of the help file to the Script window.
-s -silent Runs in silent mode; results are not sent to Results log.
83
LabTalk Scripting Guide
4.2.4.2 Examples
Using a Theme
Use the theme named FivePtAdjAve to perform a smoothing operation on the XY data in columns 1
and 2 of the active worksheet.
smooth (1,2) -t FivePtAdjAve
Note: A path does not need to be specified for the theme file since Origin automatically saves and
retrieves your themes. Themes saved in one project (*.OPJ) will be available for use in other projects
as well.
Set the output column of the freqcounts X-Function to automatically recalculate when data in the
input column changes.
freqcounts irng:=col(1) min:=0 max:=50 stepby:=increment inc:=5
end:=0 count:=1 center:=1 cumulcount:=0 rd:=col(4) -r 1;
// Set Recalculate to Auto with '-r 1'.
While running an X-Function from script it may be desirable to open the dialog to interactively supply
input. In this simple example, we perform a smoothing operation using a percentile filter (method:=2)
and specifying a moving window width of 25 data points. Additionally, we open the dialog (-d)
associated with the smooth X-Function allowing the selection of input and output data, among other
options.
smooth method:=2 npts:=25 -d
Use an FFT filter with the -cf option switch to format the output data to match that of the input data:
84
Calling X-Functions and Origin C Functions
85
LabTalk Scripting Guide
}
}
Example
Use option to scan the .h files in the OC file being loaded, and all other dependent OC files are also
loaded automatically:
// Load and compile Origin C function in the file iw_filter.c
// with the option=16, so to also load all dependent Orign C
// files by scanning for .h files included in iw_filter.c
if(run.LoadOC(OriginLab\iw_filter.c, 16) != 0)
{
type "Failed to load iw_filter.c!";
return 0;
}
Now, open Code Builder by menu View: Code Builder, and in the Workspace panel (if not see this
panel, open by View: Workspace menu item in Code Builder) of Code Builder, you can see the
iw_filter.c file is under the Temporary folder.
86
Calling X-Functions and Origin C Functions
Once a file has been opened in Code Builder, one can simply drag and drop the file to the System
branch of the Code Builder workspace. This will then ensure that the file will be loaded and compiled
in each new Origin session. For more details, please refer to Code Builder documentation.
You can programmatically add a source file to the system folder so that it will be available anytime
Origin is run.
run.addOC(C:\Program Files\Originlab\Source Code\MyFunctions.c);
This can be useful when distributing tools to users or making permanently available functions that
have been designed to work with Set Column Values.
bool (true or No, pass int instead, 0 for false, and other No, return int instead, 0 for
false) integer for true. false, 1 for true.
int, double
Yes Yes
array
87
LabTalk Scripting Guide
2. In Code Builder, create a new *.c file by menu File: New. In the New File dialog, give a file
3. Start a new line at the end of this new file, and add the following code.
88
Calling X-Functions and Origin C Functions
5. If no error, the function defined above is now available in LabTalk. Run the following script in
89
5 Running and Debugging LabTalk Scripts
LT Running Scripts
LT Debugging Scripts
Origin provides several options for executing and storing LabTalk scripts. The first part of this chapter
profiles these options. The second part of the chapter outlines the script debugging features
supported by Origin.
From Files
ProjectEvents Script
91
LabTalk Scripting Guide
From Console
On A Timer
92
Running and Debugging LabTalk Scripts
While there are many places in Origin that scripts can be stored and run, they are not all equally
likely. The following sub-sections have been arranged in an assumed order of prevalence based on
typical use.
The first two, on (1) Running Scripts from the Script and Command Windows and (2) Running Scripts
from Files, will be used much more often than the others for those who primarily script. If you only
read two sub-sections in this chapter, it should be those. The others can be read on an as-needed
basis.
Origin also has a native script editor, Code Builder, which is designed for editing and
debugging both LabTalk and Origin C code. To access Code Builder, enter ed.open()
into the script or command window, or select the button from the Standard
Toolbar.
93
LabTalk Scripting Guide
1. Open the Origin.ini file in User Files Folder, search for the [font] section: paste
2. Restart the Origin and check the Script Window again, the font and size both
changed.
ScriptWindowFontHeight=24
ScriptWindowCharset=0
ScriptWindowFaceName=Times New Roman
For more charset value, see http://msdn.microsoft.com/en-us/library/cc250412.aspx
An OGS file can also be attached to the Origin Project (OPJ) rather than saving it to
disk. The file can be added to the Project node in Code Builder and will then be saved
with the project. Drag the filename from the User folder and drop into the Project
folder. Script sections in such attached OGS files can be called using the
run.section() object method similar to calling sections in a file saved on disk. Only the
file name needs to be specified, as Origin will first look for the file in the project itself
and execute the code if filename and section are found as attachments to the project.
94
Running and Debugging LabTalk Scripts
Command Error occurs. The framework of a typical multi-section OGS file might look like the
following:
[Main]
// Script Lines
ty In section Main;
[Section 1]
// Script Lines
ty In section 1;
[Section 2]
// Script Lines
ty In section 2;
Note here that ty issues the type command, which is possible since no other commands in Origin
begin with the letters 'ty'.
95
LabTalk Scripting Guide
When using run.section, a comma must separate the section name from the first argument
only.
When you pass literal text or string variables as arguments, each argument must be
surrounded by quotation marks (in case the argument contains more than one word, or is a
negative value). Passing numbers or numeric variables doesn't require quotation mark
You can pass up to five arguments, separated by Space, to script file sections or macros. In
the script file section or macro definition, argument placeholders receive the passed arguments.
These placeholders are %1, %2, %3, %4, and %5. The placeholder for the first passed
argument is %1, the second is %2, etc. These placeholders work like string variables in that
they are substituted prior to execution of the command in which they are embedded. The
As an example of passing literal text as an argument that is received by %1, %2, etc., Suppose a
TEST.OGS file includes the following section:
[output]
type "%1 %2 %3";
and you execute the following script:
run.section(test.ogs, output, "Hello World" from LabTalk);
Here, %1 holds "Hello World", %2 holds "from", and %3 holds "LabTalk". After string substitution,
Origin outputs
Hello World from LabTalk
to the Script window. If you had omitted the quotation marks from the script file section call, then %1
would hold "Hello", %2 would hold "World", and %3 would hold "from". Origin would then output
Hello World from
Passing numeric variable arguments by reference allows the code in the script file section or macro to
change the value of the variable.
For example, suppose your application used the variable LastRow to hold the row number of the last
row in column B that contains a value. Furthermore, suppose that the current value of LastRow is 10.
If you pass the variable LastRow to a script file section whose code appends five values to column B
(starting at the current last row), after appending the values, the script file section could increment the
value of the LastRow variable so that the updated value of LastRow is 15.
96
Running and Debugging LabTalk Scripts
See example:
If a TEST.OGS file includes the following section:
[adddata]
loop (n, 1, 5)
{
%1[%2 + n] = 100;
};
%2 = %2 + (n - 1);
return 0;
And you execute the following script:
col(b) = data(1, 10); // fill data1_b with values
get col(b) -e lastrow; // store last row of values in lastrow
run.section(test.ogs, adddata, col(b) lastrow);
lastrow = ;
Then LastRow is passed by reference and then updated to hold the value 15.
Passing numeric variable arguments by value is accomplished by using the $() substitution notation.
This notation forces the interpreter to evaluate the argument before sending it to the script file section
or macro. This technique is useful for sending the value of a calculation for future use. If the
calculation were sent by reference, the entire expression would require calculation each time it was
interpreted.
In the following script file example, numeric variable var is passed by reference and by value. %1 will
hold the argument that is passed by reference and %2 will hold the argument that is passed by value.
Additionally, a string variable (%A) consisting of two words is sent by value as a single argument
to %3.
[typing]
type -b "The value of %1 = %2 %3";
return 0;
Save the section to Test.OGS and run the following script on command window:
var = 22;
%A = "degrees Celsius";
run.section(test.ogs, typing, var $(var) "%A");
Then a dialog box pop-up and says: "The value of var = 22 degrees Celsius".
There is no restriction on the length or type of characters used to name the OGS file.
Specifying the filename extension is optional for files with the OGS extension.
When using run.section( ) inside an OGS file to call another section of that same OGS file, the
97
LabTalk Scripting Guide
[main]
run.section( , calculate);
[calculate]
cc = aa + bb;
The name of the OGS file must conform to the restrictions on command names: 25 characters
or fewer, must not begin with a number or special character, must not contain spaces or
underscore characters.
2. If no main section is found, but code exists at the beginning of the file without a
Do not give an OGS file the same name as an existing Origin function or X-Function!
98
Running and Debugging LabTalk Scripts
In the case or run.section( ) scripts can reside in subfolders of the User Files Folder and you can use
relative referencing such as:
run.section(subfolder1\scriptA,main); // ScriptA.ogs is in subfolder1
run.section(subfolder2\scriptA,main); // ScriptA.ogs is in subfolder2
You can set the Current Working Folder from script. For example, to run an OGS file named
ave_curves.ogs, located in the Origin system sub-folder Samples\LabTalk Script Examples, enter
the following:
// Create a string variable to hold the complete path to the desired
//script file
// by appending folder path to Origin system path:
path$ = system.path.program$ + "Samples\LabTalk Script Examples\";
// Make the desired path the current directory.
cd path$;
// Call the function
ave_curves;
You can create a set of pre-defined paths. The cdset X-Function is used to list all the pre-defined
paths and add/change the CWF. By typing
// The 'cdset' command displays pre-defined paths
//in the Script Window.
cdset
you should see three paths like below if you have not changed them yet.
Folder paths added to the pre-defined set in one project are saved for use with
other projects.
To see the current paths displayed to the Script Window, enter 'cdset' by itself
99
LabTalk Scripting Guide
A new path, assigned to an index for which a current path exists, will overwrite
As the three default pre-defined paths show above, the second one contains several sample script
files (with the OGS extension). Similar to DOS, you can go to this folder by cd 2, then see the valid
OGS using the dir X-Function, and then run any available script file in this folder, such as:
// Set 2nd folder as the CWF
cd 2;
// List all ogs and X-Function in the CWF
dir;
// Run a script file
// Note that the file extension is not needed when calling it
autofit;
You can also load the script file in the CWF into Code Builder by using ed.open() method. Such as:
// In this case, the OGS extension on the filename is required!
ed.open(pick_bad_data.ogs)
100
Running and Debugging LabTalk Scripts
In the Before Formula Scripts section of the Set Column Values dialog, a script can be entered
that will be executed by Origin just before the formula itself is executed. This feature is useful for
carrying out operations that properly setup the formula itself. The following example demonstrates the
use of such a script:
// In column BaseNormal
// In the expression section ..
BN
// In the Before Formula Scripts section ..
range raR = col(Reading); // The signal
range raB = col(Baseline); // The Baseline
dataset BN;
BN = raR - raB; // Subtract the baseline from the signal
stats BN; // Get statistics of the result
BN /= (stats.max / 100); // Normalize to maximum value of 100
The following image is a screenshot of the code above entered into the Set Column Values dialog:
101
LabTalk Scripting Guide
Here is a script that is attached to Sheet3 which is set to run on Import (into Sheet3) or when the A
column of Sheet2 changes.
range ra1 = Sheet1!1;
range ra2 = Sheet1!2;
range ra3 = Sheet2!A; // Our 'Change in Range' column
range ra4 = 3!2; // Import could change the sheet name ..
range ra5 = 3!3; // .. so we use numeric sheet references
ra5 = ra3 * ra2 / ra1 * ra4;
Enter to execute.
Like the Command Window, there is a history of what has been executed.
Unlike the Script window, whose content is not saved when Origin closes, these scripts are
// Scale column 2 by 10
col(2)*=10;
5.2.7.1 Buttons
Some of your scripts may be used so often that you would like to automate their execution by
assigning one or more of them to a button on the Origin project's graphical-user interface (GUI). To
do so, follow the steps below:
From a new open Origin project:
1. Select the text tool from the tool menu on the left side of the project window -->
2. Now click in the open space to the right of the two empty columns of the blank worksheet in the
Book1 window. This will open a text box. Type "Hello" in the text box and click outside the box-
102
Running and Debugging LabTalk Scripts
3. Now hold down the ALT key while double-clicking on the text that you just created. A window
4. Not that there is an Object Name in the upper left of the dialog. Change this to Greeting.
5. In the lower text box of the Programming Control window, enter our script:
7. You have now created a button that, when pressed, executes your script and prints "Hello
Unlike a text script which exists only in the Classic Script Window, this button and the script it runs
will be saved when you save your Origin project.
The script behind any graphic object an be run using its name and the run method. Open the
Command Window and type:
greeting.run()
and press Enter.
5.2.7.2 Lines
Here is a script that creates a vertical line on a graph that can be moved to report the interpolated
value of your data at the X position represented by the line:
// Create a vertical line on our graph
draw -n MyCursor -l -v $(x1+(x2-x1)/2);
MyCursor.HMOVE = 1; // Allow horizontal movement
MyCursor.color = color(orange); // Change color to orange
MyCursor.linewidth = 3; // Make line thicker
// Add a label to the graph
label -sl -a $(MyCursor.x) $(Y2+0.05*(Y2-Y1)) -n MyLabel $(%C(MyCursor.x));
// Assign a script to the line ..
MyCursor.script$="MyLabel.x = MyCursor.x;
MyLabel.y = Y2 + MyLabel.dy;
doc -uw;";
// .. and make the script run after the line is moved
MyCursor.Script = 2;
2. Use the Back(data) tool on the Object Edit toolbar to push the rectangle behind the data.
103
LabTalk Scripting Guide
3. Hold down the Alt key and double-click on the rectangle to open Programming Control. Note
%B = %C;
%A = xof(%B);
dataset dsRect;
dsRect = ((%A >= rect.x1) && (%A <= rect.x2) &&
(%B >= rect.y3) && (%B <= rect.y1))?%B:0/0;
stats dsRect;
delete dsRect;
type -a Mean of $(stats.mean);
5. Choose the Moved or Sized event in the Script, Run After drop down list.
6. Click OK.
When you Move or Resize this rectangle, the script calculates the mean of all the points within the
rectangle and types the result to the Script Window. You can also define a Graphic Object range and
run the script like:
GObject gobj = [Graph1]1!rect;
gobj.run();
104
Running and Debugging LabTalk Scripts
drop-down menu, and select the Execute Current Section option. Then in the Origin Script Window,
issuing the list a command will confirm that the new function appears and is available for use in the
project.
A brief tutorial in the Functions demonstrates the value of ProjectEvents.ogs when used in
conjunction with LabTalk's dataset-based functions.
You can add your own sections to this OGS file to save custom routines or project-
specific script code. Such sections will not be event-driven, but can be accessed by
name from any place that LabTalk script can be executed. For example, if you add a
section to this file named [MyScript], the code in that section can be executed after
opening the project by issuing this command from the script window:
run.section(projectevents,myscript);
A ProjectEvents.ogs script can also be made to run by opening the associated Origin Project (OPJ)
from a command console external to Origin.
2. Browse to the Origin Samples\Spectroscopy folder and choose Peaks with Base.DAT.
6. Enter an appropriate Filter file name, such as Subtract Base and Find Peaks.
8. Click Next.
105
LabTalk Scripting Guide
$(raSubtracted[pkidx]);
}
10. Click Finish.
After the import, the script runs which creates the subtracted data and the pkFind function
// Get the tree from the last Report Sheet (this fit)
getresults iw:=__REPORT$;
106
Running and Debugging LabTalk Scripts
oa.Exit
Set oa = Nothing
End
There are more detailed examples of COM Client Applications in the Samples\COM Server and
Client folder.
5.2.13 On A Timer
The Timer (Command) executes the TimerProc macro, and the combination can be used to run a
script every n seconds.
The following example shows a timer procedure that runs every 2 seconds to check if a data file on
disk has been modified, and it is then re-imported if new.
In order to run this scipt example, perform the following steps first:
1. Create a simple two-column ascii file c:\temp\mydata.dat or any other desired
2. Start a new project and import the file into a new book with default ascii settings.
107
LabTalk Scripting Guide
3. Create a line+symbol plot of the data, and set the graph x and y axis rescale
ProjectEvents.OGS:
timer -k;
7. Save the Origin Project, close, and then re-open the project. Now any time the
project is opened, the timer will start, and when the project is closed the timer
8. Go to the data file on disk and edit and add a few more data points
9. The timer procedure will trigger a re-import and the graph will update with the
108
Running and Debugging LabTalk Scripts
Use the [Startup] section of the Origin.ini to define global constants, variables and functions for use
any time you run Origin.
See these topics for more information on scope:
Scope of Variables
Scope of Functions
See FAQ-286 for information on defining constants and variables for use across Origin sessions.
2. Start a fresh page in a text editor (e.g. Notepad) and enter the following information:
[Main]
@global = 1;
// This function calculates the cube root of a number
function double dCubeRoot(double dVal)
{
double xVal;
if(dVal<0) xVal = -exp(ln(-dVal)/3);
else xVal = exp(ln(dVal)/3);
return xVal;
}
@global = 0;
3. Name and save the file to your the User Files Folder (UFF), using an .OGS file extension (e.g.
myLTFuncs.ogs).
4. Browse to your Origin.ini file in your UFF and open this file in your text editor.
5. Locate the [Startup] section of the file and add the name of the .OGS file you just created
FileN=myLTFuncs.ogs
109
LabTalk Scripting Guide
8. To check the availability of your function, run Origin, open the Script Window and enter the
name of the function, followed by a value in parentheses and "=", then press ENTER.
dCubeRoot(8)=
9. Origin returns:
dCubeRoot(8)=2
See this topic for more information on the Scope of Functions.
When the Origin application is launched, there are multiple events that are triggered. Your LabTalk
script can be set to execute with each event using the OEvents.OGS file. This OEvents.OGS file
includes several sections that indicate when to run the script, such as, [AfterCompileSystem],
[BeforeOpenDoc], and [OnExitOrigin].
The following example demonstrates cleaning the history panel of Command Window on existing
Origin.
(Note that Origin C functions can not be run in the [OnExitOrigin] section. If you want to trigger
events on exiting Origin, always use LabTalk commands.)
1. Copy the OEvents.OGS file from the Origin EXE folder to your User Files Folder. Alternatively,
when opening the file from the EXE folder just make sure to then save it to your User Files
Folder.
// Delete the files, which keep the history of command window, from the
User File folder
del -f "%YUpDown_Buffer.txt";
del -f "%YLTHistory.txt";
3. To run sections in OEvents.OGS, you also need to edit the Origin.ini file in your User Files
Folder. Close Origin if running, and then edit your Origin.ini and uncomment (remove the ";") in
Ogs1 = OEvents
; Ogs2 = OEvents
; Origin can trigger multiple system events
; Uncomment this line and implement event handlers in OEvents.ogs
Note: More than one event handler file may exist in Origin.ini and the name is not restricted
to OEvents.OGS.
5. Close Origin and restart a new Origin session to check whether the history panel of Command
Window is clean.
110
Running and Debugging LabTalk Scripts
2. A LabTalk script file that will be executed when the user clicks the button.
3. An INI file that stores information about the button or button group. Origin creates the INI file for
We will assume for now that you have a bitmap image file (BMP) that will define the button itself (if
you are interested in creating one, example steps are given below).
First, use CodeBuilder (select on the Origin Standard Toolbar to open) or other text editor, to
develop your LabTalk script (OGS) file. Save the file with the OGS extension. You may divide a single
script file into several sections, and associate each section with a different toolbar button.
3. Click the New button in the Button Group to open the Create Button Group dialog.
111
LabTalk Scripting Guide
6. Click the Browse button to locate your bitmap file. This file should be in your User directory.
7. Click OK.
8. The Save As dialog will open. Enter the same name as that of your bitmap file. Click OK to
save the INI file. You will now see that your group has been added to the Groups list and your
When creating a custom button group for export to an OPX file, consider saving your button group's
initialization file, bitmap file(s), script file(s), and any other support files to a user-created subfolder in
your User Files folder. When another Origin user installs your OPX file, your custom subfolder will
automatically be created in the user's User Files folder, and this subfolder will contain the files for the
custom button group. This allows you to keep your custom files separate from other Origin files.
4. Enter the Section Name of the OGS file and any arguments in the Argument List.
7. Click OK.
8. Repeat these steps for each of the buttons in your Button Group.
9. Drag the first button out onto your Origin workspace. A toolbar is created. You can now drag all
112
Running and Debugging LabTalk Scripts
Drag any of these buttons onto the Origin toolbar to begin using them. Use the procedure outlined
above to associate a script with a given button.
1. Using the bitmap for the built-in user defined toolbar is a good place to begin. In Windows
Paint, select File:Open, browse to your User Files folder and select Userdef.bmp.
2. Set the image size. Select Image:Attributes. The height needs to remain at 16 and should not
be changed. Each button is 16 pixels high by 16 pixels wide. If your toolbar will be only 2
buttons then change the width to 32. The width is always 16 times the number of buttons, with
113
LabTalk Scripting Guide
4. Select View:Zoom:Show Grid. You can now color each pixel. The fun begins - create a look
5. Select File:Save As, enter a new File name but leave the Save as type to 16 Color Bitmap.
Interactive Execution
Debugging Tools
Error Handling
This window can be open from the Window main menu. This is the most flexible place for advanced
users to execute LabTalk scripts. Enter key will execute
1. the current line if cursor has no selection
114
Running and Debugging LabTalk Scripts
You can use Ctrl+Enter to add a line without executing. There is also a Script Execution option on
the Edit menu to toggle between editing and interactive execution.
You can enter a LabTalk command at the command prompt in the Command Window. The result
would be printed immediately after the entered command line. Command Window has various
convenient features such as command history panel, auto-completion, roll back support for utilizing
previously executed commands, saving previously executed commands to an OGS file, etc. Note,
however, that you cannot edit multi-line scripts within the Command Window.
To learn how to use the Command window, see The Origin Command Window chapter in the
Origin help file.
Code Builder is Origin's integrated development environment useful in debugging LabTalk scripts as
well as Origin C code, X-Function code, etc. In Code Builder, use various convenient debugging tools
like setting up break points, step-by-step execution, inspection of the values of variables, etc.
To learn how to use the Code Builder, see the Code Builder User's Guide in the Programming help
file.
115
LabTalk Scripting Guide
3. Place the cursor on line 12 - the [Main] section - then select menu Debug: Execute Current
Section. The [Main] section code will run and stop at the line with the break point.
4. Now press F10 to execute the remaining script line by line. Code Builder provides the Watch
window to view the value of a variable during debugging. For example, after pressing F10 once,
open the Watch window by menu item View: Watch if it is not opened yet. Then type fname$
in the left cell of the table in this window, the value will show in the right cell of the same row.
5. To execute the remaining script, press F5. It will complete unless encountering another break
point.
5.3.3.2 Ed (object)
116
Running and Debugging LabTalk Scripts
The Ed (object) provides script access to Code Builder, a dedicated editor for LabTalk script and
Origin C code.
The ed object methods are:
Method Brief Description
ed.open(fileName, Open the specified OGS file at the specified section in the Code
sectionName) Builder window. (Defaults to file beginning if section not found.)
ed.open()
The list command with no options as well as the ed command (different than the ed object) opens
the LabTalk Variables dialog, which is a table of attributes for all variables in the current project. The
attributes are variable name, value, type, subtype, property, plot information, and description.
This is a useful tool for script programmers as the current values and properties of variables can be
viewed in real time. Additionally, variables can be sorted by any of their attributes, alphabetically in
the case of text descriptors, numerically in the case of numeric values.
Check boxes exist on the right-hand side of the dialog that allow you to see any subset of the entire
variable list.
117
LabTalk Scripting Guide
2 Display scripts that have been sent to the queue for delayed execution;
16 Display macros.
These values are bits that can be combined to produce cumulative effects. For example, echo = 12
displays both command and assignment scripts. Echo = 7 (includes echo = 1, echo = 2, and echo =
4) is useful for following script execution during menu command selection. To disable echo, type echo
= 0 in the Script window
118
Running and Debugging LabTalk Scripts
@B = 1;
range rr = [Book1]Sheet1!col(A); // Range to column A
for (ii=1; ii<=10; ii+=1) {
#!ii=; rr[ii]=; // Embedded debugging script
rr[ii]+=ii*10;
}
@B = 0;
#!type -a This line will not execute
The script sets @B equal to 1 to allow #! lines to execute. By setting @B to 0 , the last line will not
execute.
119
LabTalk Scripting Guide
when you click the No button in dialog boxes that do not have a Cancel button.
120
Running and Debugging LabTalk Scripts
121
LabTalk Scripting Guide
122
6 String Processing
String Processing
String Arrays
123
LabTalk Scripting Guide
In this example, a string method designed for a very specific but commonly needed task is invoked.
// Use the built-in string method, GetFileName():
string fname$="C:\Program Files\Origin 8\Samples\Import\S15-125-03.dat";
string str1$ = fname.GetFileName()$;
str1$=;
Here, another variation of generic finding methods is chosen to complete the task.
// Use a token-based method to extract the file name:
124
String Processing
%A="Left";
%B="Handed";
%N="%A %B";
%N= // "Left Handed"
// Extract the file name substring from the longer file path string:
%N="C:\Program Files\Origin 8\Samples\Import\S15-125-03.dat";
for(done=0;done==0; )
{
%M=%[%N,>'\'];
if(%[%M]>0) %N = %M;
else done = 1;
}
%N=;
int nn=fname.Find('S');
string str1$ = fname.Mid(nn+1, 2)$;
type "1st number = %(str1$)";
int nn = fname.ReverseFind('-');
int oo = fname.ReverseFind('.') ;
string str3$ = fname.Mid(nn + 1, oo - nn - 1)$;
type "3rd number = %(str3$)";
125
LabTalk Scripting Guide
126
String Processing
127
LabTalk Scripting Guide
y = 1.1
The result has only 2 siginificant digits, because y is followed by *4* instead of *4.
6.5.2.4 Use the $(x, S*n) notation to convert from engineering to scientific
notation
In this syntax, n specifies the total number of digits.
x = 1.23456;
type "x = $(x,S*3)";
And Origin returns:
x = 1.23E0
128
String Processing
129
7 Workbooks Worksheets and Worksheet Columns
LT Workbooks
LT Worksheets
LT Worksheet Columns
7.2 Workbooks
7.2.1 Workbooks
Workbook Manipulation
131
LabTalk Scripting Guide
newbook MyResultBook;
132
Workbooks Worksheets and Worksheet Columns
// Create a project
string strOpj$ = system.path.program$ + "Samples\Analysis.opj";
doc -o %(strOpj$);
// close this workbook without prompting, and delete all the data
win -cd %H;
// Use -hc to hide the first workbook (not the active one), MyBook1
// And the View Mode in Project Explorer is Hidden
win -hc 1 MyBook1;
// To show MyBook1 and MyBook3, need to use the -hc switch to specify
// the workbook name
win -hc 0 MyBook1;
133
LabTalk Scripting Guide
134
Workbooks Worksheets and Worksheet Columns
doc -o %(strOpj$);
doc -o %(strOpj$);
135
LabTalk Scripting Guide
doc -o %(strOpj$);
7.3 Worksheets
7.3.1 Worksheets
136
Workbooks Worksheets and Worksheet Columns
Virtual Matrix
When a worksheet is active, you can type wks.= and press Enter to list all worksheet properties.
Most of these properties are writable so you can modify it directly. For example:
// Rename the active worksheet
wks.name$ = Raw Data;
// Set the number of columns to 4
wks.ncols = 4;
// Modify the column width to 8 character
wks.colwidth = 8;
// Show the first user-defined parameter on worksheet header
wks.userparam1 = 1;
137
LabTalk Scripting Guide
Two properties, wks.maxRows and wks.nRows are similar. The former one find the largest row index
that has value in the worksheet, while the later set or read the number of rows in the worksheet. You
can see the different in the following script.
newbook; // Create a new workbook
col(b) = {1:10}; // Set column B with 1-10 for the first ten rows
wks.maxRows = ;
wks.nRows = ;
Origin outputs 10 for wks.maxRows; while outputs 32 for wks.nRows.
If the worksheet is not the active one, you can specify the full worksheet name (including workbook
name) before wks object, the syntax is
[WorkbookName]WorksheetNameOrIndex!wks
Or you can use the range of the worksheet. For example
// Open a project
string strOpj$ = system.path.program$;
strOpj$ += "Samples\COM Server and Client\Basic Stats on Data.opj";
doc -o %(strOpj$);
// Use range
range rWks = [RawData]Data!; // Range for the Data worksheet in RawData
workbook
rWks.userparam1 = 1; // Show the first user-defined parameter in worksheet
Using X-Functions
Besides wks object, you can also use X-Functions to modify worksheet properties. These X-Function
names are usually with the starting letter "w". Such as wcolwidth, wcellformat and wclear, etc. So we
can also resize the column with as below without using wks.colwidth:
wcolwidth 2 10; // Set the 2nd column width to 10
138
Workbooks Worksheets and Worksheet Columns
Copy a Worksheet
The wcopy X-Function is used to create a copy worksheet of the specified worksheet.
The following example duplicates the current worksheet, creating a new workbook with the copied
worksheet:
wcopy 1! [<new>]1!;
The wrcopy X-Function is used to copy a range of cells from one worksheet to another. It also allows
you to specify a source row to be used as the Long Names in the destination worksheet.
The following script copies rows from 5 to 9 of [book1]sheet1! to a worksheet named CopiedValues in
Book1 (if the worksheet does not exist it will be created), and assigns the values in row 4 from
[book1]sheet1! to the long name of the destination worksheet, [book1]CopiedValues!
wrcopy iw:=[book1]sheet1! r1:=5 r2:=10 name:=4 ow:=CopiedValues!;
To copy column and matrix object, please refer to Copy Column and Copy Matrix Data respectively.
Examples
The following script will create a new X and Y column where the Y will be the mean value for each of
the duplicate X values.
reducedup col(B);
139
LabTalk Scripting Guide
The following script will reduce the active selection (which can be multiple columns or an entire
worksheet, independent of X or Y plotting designation) by a factor of 3. It will remove rows 2 and 3
and then rows 5 and 6, leaving rows 1 and 4, etc. By default, the reduced values will go to a new
worksheet.
reducerows npts:=3;
The following script will average every n numbers (5 in the example below) in column A and output
the average of each group to column B. It is the same as the ave LabTalk function, which would be
written as col(b)=ave(col(a),5):
reducerows irng:=col(A) npts:=5 method:=ave rd:=col(b);
You can also direct the output to a new workbook, instead of a new worksheet in the existing
workbook, by changing the following line:
wxt test:=strCond$ ow:=[<new name:="Result">]"Extracted"! num:=nExtRows;
As you can see, the only difference from the earlier code is that we have added the workbook part of
the range notation for the ow variable, with the <new> keyword. (show links and indexing to <new>
modifiers, options, like template, name, etc)
LabTalk uses * and ? characters for wildcard in string comparison. You can try changing the strCond
as follows:
string strCond$ = "rYear >= 1996 and rHP<70 and rHP>60 and rMake[i]$=*o*";
to see all the other makes of cars with the letter o.
140
Workbooks Worksheets and Worksheet Columns
delete wcol($(ii));
}
141
LabTalk Scripting Guide
At times unstacking categorical data is desirable for analysis and/or plotting purposes. The
wunstackcol X-Function is the most convenient way to perform this task from script.
In this example, categorical data is imported, and we want to unstack the data by a particular
category, which we specify with the input range irng2. The data to be displayed (by category) is
referenced by input range irng1. In this example, the column ranges are input directly, but range
variables can also be used.
// Import automobile data
newbook;
string fpath$ = "\Samples\Statistics\Automobile.dat";
string fname$ = system.path.program$ + fpath$;
impasc;
Staking categorical data is something like reverse operation of unstacking categorical data. In the
original dataset, samples belong to different groups is stored in different columns. After stacking, the
samples will be in different rows in the same column, with an additional column in the worksheet
providing the group information. You can use wstackcol to stack worksheet columns.
In the following example, we open a workbook with categorical data first. And then with the first
worksheet activated, and stack column B, C, and D by rows, including another column to be A.
// Open a workbook
string strBook$ = system.path.program$;
strBook$ += "Samples\Statistics\Body.ogw";
doc -o %(strBook$);
142
Workbooks Worksheets and Worksheet Columns
// Pivot table, row source, column source and data column are the same
// For the smaller values, it will combine them across columns
// by 10% of the total
// In the result worksheet, the column info. is put to user-defined parameter
rows
// The row name is the name of column's Long Name in source worksheet
wpivot row:=col(D)
col:=col(F)
data:=col(K)
method:=sum total:=1 sort_total:=no sum:=1
dir:=col threshold:=10 // Combine smaller values across column, by
10%
// Put column info (from column's Long Name) to user-defined
parameters row
pos:=udl udlabel:=L;
143
LabTalk Scripting Guide
wks.col1.filterenabled = 0;
Insert a link to
another cell, given
by CellName, so
cell://CellName to display its cell://[Book2]Sheet2!Col(B)[3]
contents in the
current worksheet
cell.
Insert a link to a
range, given by
RangeName,
which can be
book, sheet,
column, etc. The
contents in the
current worksheet
cell will show as a
range://RangeName
link, if clicked, the range://[Book2]Sheet2!Col(B)[3]
[DisplayedText]
corresponding
range will be
activated. If the
option
DisplayedText is
included, the
displayed text in
the cell is this text,
but not the range.
Insert a link to a
graph, given by
GraphName, so
the graph will be
displayed in the
graph://GraphName current worksheet graph://Graph1
cell. If double-click
on this cell, the
corresponding
graph window will
be activated.
144
Workbooks Worksheets and Worksheet Columns
Insert a link to a
matrix object,
given by
MatrixObjectNam
e, so the matrix
object will be
matrix://MatrixObjectNa displayed in the
matrix://[MBook1]MSheet1!2
me current worksheet
cell, as an image.
If double-click on
this cell, the
corresponding
matrix window will
be activated.
Insert a link to a
Notes window,
given by
NotesWindowNa
me. The contents
notes://NotesWindowNa
in this cell will notes://Notes
me [DisplayedText]
show as a link, if
clicked, the
corresponding
Notes window will
be activated.
Insert a link to a
LabTalk variable,
var://LabTalkVariableNa
and the value of var://MyVar
me
this variable will
show in this cell.
Insert a link to a
LabTalk string
str://LabTalkStringVaria
variable, and this str://MyBook$
ble
string will show in
this cell.
145
LabTalk Scripting Guide
If the option
DisplayedText is
included, the
help://HelpPage help://TUTORIAL.CHM/Tutorial/Import_Wizard
displayed text in
[DisplayedText] .html
the cell is this text,
but not the help
link.
Insert a link to an
image file, given
by FilePath. And
file://FilePath file://D:\Flower.jpg
the linked image
will display in the
current cell.
146
Workbooks Worksheets and Worksheet Columns
147
LabTalk Scripting Guide
To add a column to the end of the worksheet, you can use the wks.addCol() method, which will add a
column with the specified name, if the specified name is used or ignored, a generic name is chosen
for the newly added column.
// Create a new workbook
newbook;
148
Workbooks Worksheets and Worksheet Columns
149
LabTalk Scripting Guide
Plot Designation
Plot designation for a column determines how the selected data will be handled by default for plotting
and data analysis. Plot designation includes X, Y, Z, Z Error, Y Error, Label, etc. And you can change
it by using wks.col.type.
// Import data
newbook;
string fname$ = system.path.program$;
fname$ += "Samples\Matrix Conversion and Gridding\XYZ Random Gaussian.dat";
impasc;
150
Workbooks Worksheets and Worksheet Columns
Column Width
Setting a correct data format for a column helps to display the data in the column correctly, also helps
to perform operations, such plotting, data analysis, etc. properly. There are many data format
available for a column, such as Numeric, Text, Date, Time, Month, Day of Week, etc. To set format,
please use wks.col object's format property.
// Import data
newbook;
string fname$ = system.path.program$;
fname$ += "Samples\Signal Processing\Average Sunspot.dat";
impasc;
// Import data
newbook;
string fname$ = system.path.program$;
fname$ += "Samples\Curve Fitting\Enzyme.dat";
impasc;
151
LabTalk Scripting Guide
For Date and Time format, if the data stored in a column is not Julian day numbers (looks
like Date and Time format, actually is text), we cannot set the format as Date or Time
directly, or the look-like-Date-and-Time-format text will become missing value or something
incorrect. To avoid this issue, Origin provides the wks.col.setformat() method.
// Import data
newbook;
string fname$ = system.path.program$;
fname$ += "Samples\Import and Export\Custom Date and Time.dat";
impasc;
152
Workbooks Worksheets and Worksheet Columns
// Turn on sparklines for all columns except the ones with "Year" Long Name
for(ii = 2; ii <= wks.nCols; ii+=5)
{
sparklines sel:=0 c1:=ii c2:=ii+3;
}
// Delete column B
delete col(B);
Basic Arithmetic
Most often data is stored in columns and you want to perform various operations on that data in a
row-wise fashion. You can do this in two ways in your LabTalk scripts: (1) through direct statements
with operators or (2) using ranges. For example, you want to add the value in each row of column A
to its corresponding value in column B, and put the resulting values in column C:
153
LabTalk Scripting Guide
When performing arithmetic on data in different sheets, you need to use range
variables. Direct references to range strings are not supported. For example, the script
Sheet3!col(1) = Sheet1!col(1) + Sheet2!col(1); will not work!
Functions
In addition to standard operators, LabTalk supports many common functions for working with your
data, from trigonometric functions like sin and cos to Bessel functions to functions that generate
statistical distributions like uniform and Poisson. All LabTalk functions work with single-number
arguments of course, but many are also "vectorized" in that they work on worksheet columns, loose
datasets, and matrices as well. Take the trigonometric function sin for example:
// Find the sine of a number:
double xx = sin(0.3572)
// Find the sine of a column of data (row-wise):
Col(B) = sin(Col(A))
// Find the sine of a matrix of data (element-wise):
[MBook2] = sin([MBook1])
As an example of a function whose primary job is to generate data consider the uniform function,
which in one form takes as input N, the number of values to create, and then generates N uniformly
distributed random numbers between 0 and 1:
/* Fill the first 20 rows of Column B
with uniformly distributed random numbers: */
Col(B) = uniform(20);
For a complete list of functions supported by LabTalk see Alphabetic Listing of Functions.
154
Workbooks Worksheets and Worksheet Columns
When logic statement is used to set formula for columns, values such as 0.0, NANUM
(missing value) and values between -1.0E-290 to 1.0E-290 will be evaluated to be
False. For instance, LabTalk command will return a value 0 (False) instead of 1
(True).
type $(-1e-290?1:0); // Returns 0 (False)
type $(1/0?1:0); // Returns 0 (False), where 1/0 == NANUM
// Fill first column with row number, and second column with uniform random
number
col(1) = {1:32};
col(2) = uniform(32);
// Fill first column with row number, and second column with uniform random
number
col(1) = {1:32};
col(2) = uniform(32);
155
LabTalk Scripting Guide
range rr = 2;
colreverse rng:=rr;
loop(ii,1,nn){
string dd$ = Col(1)[ii]$;
string tt$ = Col(2)[ii]$;
// Store the combined date-time string just as text
Col(3)[ii]$ = dd$ + " " + tt$;
// Date function converts the date-time string to a numeric date value
Col(4)[ii] = date(%(dd$) %(tt$));
};
// Now we can convert column 4 to a true Date column
wks.col4.format = 4; // Convert to a Date column
wks.col4.subformat = 11; // Display as M/d/yyyy hh:mm:ss
156
Workbooks Worksheets and Worksheet Columns
Here, an intermediate column has been formed to hold the combined date-time as a string, with the
resulting date-time (numeric) value stored in a fourth column. While they appear to be the same text,
column C is literally just text and column D is a true Date.
Given this mathematical system, you can calculate the difference between two Date values which will
result in a Time value (the number of days, hours and minutes between the two dates) and you can
add a Time value to a Date value to calculate a new Date value. You can also add Time data to Time
data and get valid Time data, but you cannot add Date data to Date data.
Available Formats
Use the D notation to convert a numeric date value into a date-time string using one of Origin's built-
in Date subformats:
type "$(@D, D10)";
returns the current date and time (stored in the system variable @D) as a readable string:
7/20/2009 10:30:48
The D10 option corresponds to the MM/dd/yyyy hh:mm:ss format. Many other output formats are
available by changing the number after the D character, which is the index entry (from 0) in the Date
Format drop down list of the Worksheet Column Format dialog box, in the line of script above. The
first entry (index = 0) is the Windows Short Date format, while the second is the Windows Long Date
format.
Note : The D must be uppercase. When setting a worksheet subformat as in wks.col3.subformat = #,
these values are indexed from 1.
For instance
type "$(date(7/20/2009), D1)";
produces, using U.S. Regional settings,
Monday, July 20, 2009
Similarly, for time values alone, there is an analagous T notation, to format output:
type "$(time(12:04:14), T5)"; // ANS: 12:04 PM
Formatting dates and times in this way uses one specific form of the more general $() Substitution
notation.
Custom Formats
There are three custom date and time formats - two of which are script editable properties and one
which is editable in the Column Properties dialog or using a worksheet column object method.
1. system.date.customformatn$
Both methods use date-time specifiers, such as yyyy'.'MM'.'dd, to designate the custom format.
Please observe that:
The text portions (non-space delimiters) of the date-time specifier can be changed as required,
The specifier tokens themselves (i.e., yyyy, HH, etc.) are case sensitive and need to be used
exactly as shown— all possible specifier tokens can be found in the Reference Tables: Date
157
LabTalk Scripting Guide
The first two formats store their descriptions in local file storage and as such may appear
different in other login accounts. The third format stores its description in the column itself.
Dnn notation
Origin has reserved D19 to D21 (subformats 20 to 22, since the integer after D starts its count from 0)
for these custom date displays. The options D19 and D20 are controlled by system variables
system.date.customformat1$ and system.date.customformat2$, respectively. To use this option
for output, follow the example below:
To specify a custom date display for a date column which is stored in the worksheet column, use the
Wks.Col.SetFormat object method. When entering the custom date format specifier, be sure to
surround any non-date characters with single quotes. Also note that this object method works on
columns of the active worksheet only.
In the following example, column 4 of the active worksheet is set to display a custom date/time
format:
// wks.format=4 (date), wks.subformat=22 (custom)
wks.col4.SetFormat(4, 22, yyyy'-'MM'-'dd HH':'mm':'ss'.'###);
doc -uw; // Refresh the worksheet to show the change
158
8 Matrix Books Matrix Sheets and Matrix Objects
LT Matrix Sheets
LT Matrix Objects
When using X-Function newbook to create new matrix book, the argument mat must be 1.
159
LabTalk Scripting Guide
Use the same command, doc -o, as opening workbook, to open matrix book. The difference is
Origin's matrix book with data is with the extension of ogm, and template without data is otm.
To save matrix book to ogm file and otm file, the save -i command and template_saveas X-
Function will be used respectively, that is also the same with workbook. However, matrix book
This is the same as workbook, see commands win -ca and win -cd.
This is the same as workbook, see switches -ch, -h, and -hc in win command.
This is the same as workbook, see win -r command, and page object.
This is the same as workbook, see win -a command. The command window -o winName
{script} can be used to run the specified script for the named matrix book. See the opening
160
Matrix Books Matrix Sheets and Matrix Objects
matrix -it 0;
161
LabTalk Scripting Guide
Set Dimensions
Both the wks object and the mdim X-Function can be used to set matrix dimensions:
// Use the wks object to set dimension
wks.ncols = 100;
wks.nrows = 200;
// Use the mdim X-Function to set dimension
mdim cols:=100 rows:=100;
For the case of multiple matrix objects contained in the same matrix sheet, note that all of the matrix
objects must have the same dimensions.
Set XY Mapping
Matrices have numbered columns and rows which are mapped to linearly spaced X and Y values. In
LabTalk, you can use the mdim X-Function to set the mapping.
// XY mapping of matrix sheet
mdim cols:=100 rows:=100 x1:=2 x2:=4 y1:=4 y2:=9;
162
Matrix Books Matrix Sheets and Matrix Objects
// Insert a matrix object before the 1st one in the active matrix sheet
wks.insert();
163
LabTalk Scripting Guide
newbook mat:=1;
164
Matrix Books Matrix Sheets and Matrix Objects
165
LabTalk Scripting Guide
Two X-Functions, m2v and v2m, are available for converting matrix data into a vector, and vector
data into a matrix, respectively. Origin uses row-major ordering for storing a matrix, but both functions
allow for column-major ordering to be specified as well.
// Copy the whole matrix, column by column, into a worksheet column
m2v method:=m2v direction:=col;
// Copy data from col(1) into specified matrix object
v2m ix:=col(1) method:=v2row om:=[Mbook1]1!1;
When a matrix contains an image in a matrix, the X-Function mcrop can be used to extract or crop to
a rectangular region of the matrix.
// Crop an image matrix to 50 by 25 beginning from 10 pixels
// from the left and 20 pixels from the top.
mcrop x:=10 y:=20 w:=50 h:=25 im:=<active> om:=<input>; // <input> will crop
// Extract the central part of an image matrix to a new image matrix
// Matrix window must be active
matrix -pg DIM px py;
dx = nint(px/3);
dy = nint(py/3);
mcrop x:=dx y:=dy h:=dy w:=dx om:=<new>; // <new> will extract
166
Matrix Books Matrix Sheets and Matrix Objects
The X-Function mexpand can expand a data matrix using specified column and row factors.
Biquadratic interpolation is used to calculate the values for the new cells.
// Expand the active matrix with both factor of 2
mexpand cols:=2 rows:=2;
The X-Function mflip can flip a matrix horizontally or vertically to produce its mirror matrix.
// Flip a matrix vertically
mflip flip:=vertical;
With the X-Function mrotate90, you can rotate a matrix 90/180 degrees clockwise or
counterclockwise.
// Rotate the matrix 90 degrees clockwize
mrotate90 degree:=cw90;
The X-Function mshrink can shrink a data matrix by specified row and column factors.
// Shrink the active matrix by column factor of 2, and row factor of 1
mshrink cols:=2 rows:=1;
167
LabTalk Scripting Guide
Sometimes user may not want to create a new Matrixbook for output in X-Function each time when
performing intermediate matrix analysis operations. He can create a temporary matrix in a hidden
Matrixbook for intermediate output, and delete the Matrixbook when it is not needed in next operation.
Example 1
This example shows how to save intermediate image operation result in a temporary Matrixbook, and
delete it in the next step.
//Import an image into Origin's Matrixbook
string fn$=system.path.program$ + "Samples\Image Processing and
Analysis\white camellia.jpg";
impImage fname:=fn$;
//Create a hidden Matrixbook
newbook hidden:=1 mat:=1;
%A = bkname$;
//Perform Auto Level operation and save the output in the hidden Matrixbook
imgAutoLevel oimg:=[%A]1! cl:=<optional>;
//Apply Median filter on the image from Auto Level operation
imgMedian d:=3 img:=[%A]1! oimg:=<new>;
//Delete the intermediate matrix
win -cd %A;
Example 2
In this example, a median filter was applied on a matrix, and the volume was calculated after the
minimum was subtracted. All intermediate matrix results were saved in a hidden temporary
Matrixbook, and the Matrixbook was deleted after it was not needed.
//Open a sample Matrixbook
string fn$=system.path.program$ + "Samples\Matrix Conversion and Gridding\2D
Gaussian.ogm";
doc -o %(fn$);
//Create a temporary hidden Matrixbook
newbook hidden:=1 mat:=1;
%A = bkname$;
range rm = [%A]1!;
//Add two matrix objects to receive two intermediate matrix results
rm.nmats = 2;
//Apply a median filter on a matrix
medianflt2 n:=3 po:=RepeatPadding om:=[%A]1!mat(1);
//Subtract the minimum
msetvalue im:=[%A]1!mat(2) formula:="mat(1)-z0" script:="double z0; mstats
im:=mat(1) min:=z0;";
//Integrate the matrix
double dv;
integ2 im:=[%A]1!mat(2) integral:=dv;
win -cd %A;
168
Matrix Books Matrix Sheets and Matrix Objects
Data in a matrix can also be converted to a worksheet by using the m2w X-Function. This X-Function
can directly convert data into worksheet, with or without X/Y mapping, or convert data by rearranging
the values into XYZ columns in the worksheet.
The following example shows how to convert matrix into worksheet, and plot graphs using different
methods according the form of the worksheet data.
// Create a new matrix book
win -t matrix;
// Set matrix dimension and X/Y values
mdim cols:=21 rows:=21 x1:=0 x2:=10 y1:=0 y2:=100;
// Show matrix X/Y values
page.cntrl = 2;
// Set matrix Z values
msetvalue formula:="nlf_Gauss2D(x, y, 0, 1, 5, 2, 50, 20)";
// Hold the matrix window name
%P = %H;
// Covert matrix to worksheet by Dierct method
m2w ycol:=1 xlabel:=row1;
// Plot graph from worksheet using Virtual Matrix
plotvm irng:=1! format:=1 ztitle:=MyGraph type:=242 ogl:=<new
template:=cmap>;
// Convert matrix to XYZ worksheet data
sec -p 2;
win -a %P;
m2w im:=!1 method:=xyz;
// Plot a 3D Scatter
worksheet -s 3;
worksheet -p 240 3D;
If the matrix data is converted directly to worksheet cells, you can then plot such worksheet data
using the Virtual Matrix feature.
169
9 Graphing
9.1 Graphing
Creating Graphs
Formatting Graphs
Managing Layers
Origin's breadth and depth in graphing support capabilities are well known. The power and flexibility
of Origin's graphing features are accessed as easily from script as from our graphical user interface.
The following sections provide examples of creating and editing graphs from LabTalk scripts.
200 Line
201 Scatter
202 Line+symbol
203 column
All of the possible values for the plot option can be found in the Plot Type IDs.
171
LabTalk Scripting Guide
The following example plots the first two columns of data in the active worksheet, where the first
column will be plotted as X and the second column as Y, as a line plot.
plotxy iy:=(1,2) plot:=200;
The following example plots the second column of data in the active worksheet, as Y against its
associated X, as a line plot. When you do not explicitly specify the X, Origin will use the the X-column
that is associated with that Y-column in the worksheet, or if there is no associated X-column, then an
<auto> X will be used. By default, <auto> X is row number.
plotxy iy:=2 plot:=200;
172
Graphing
// Plot the first and third columns as X and Y into the second layer
// Now that the graph window is the active window, need to specify Book
//and Sheet
plotxy iy:=[bkname$]shname$!(1,3) plot:=202 ogl:=2;
// Plot by group
plotgroup iy:=(4,5) pgrp:=Col(3);
This next example creates graph windows based on one group and graph layers based on a second
group:
// Bring in Sample data
fn$ = system.path.program$ + "Samples\Graphing\Categorical Data.dat";
newbook;
impASC fn$;
// Sort
dataset sortcol = {4,3}; // sort by drug, then gender
dataset sortord = {1,1}; // both ascending sort
wsort nest:=sortcol ord:=sortord;
// Plot each drug in a separate graph with gender separated by layer
plotgroup iy:=(2,1) pgrp:=col(drug) lgrp:=col(gender);
173
LabTalk Scripting Guide
Note : Each group variable is optional. For example, you could use one group variable to organize
data into layers by omitting Page Group and Data Group. The same sort order is important for
whichever options you do use.
174
Graphing
When you have a range variable mapped to a graph page or graph layer, you can use
that variable name in place of the word page or layer.
175
LabTalk Scripting Guide
If you wish to work with the Y scale, then simply change the x in the above script to a
y. If you wish to work with a layer that is not active, you can specify the layer index,
layerN.x.from. Example: layer3.y.from = 0;
The Axis command can also be used to access the settings in the Axis dialog.
To change the X Axis Tick Labels to use the values from column C, given a plot of col(B) vs. col(A)
with text in col(C), from Sheet1 of Book1:
range aa = [Book1]Sheet1!col(C);
axis -ps X T aa;
176
Graphing
Remember that when using X-Functions you do not always need to use the variable
name when assigning values; however, being explicit with col:= and row:= may make
your code more readable. To save yourself some typing, in place of the code above,
you can use the following:
newpanel 2 3;
177
LabTalk Scripting Guide
// Import a file
path$ = system.path.program$ + "Samples\Graphing\";
fname$ = path$ + "waterfall2.dat";
impasc;
The following example will add an independent right Y axis scale. A new layer is added, displaying
only the right Y axis. It is linked in dimension and the X axis is linked to the current active layer at the
time the layer is added. The new added layer becomes the active layer.
layadd type:=rightY;
The following example will arrange the existing layers on the active graph into two rows by three
columns. If the active graph does not already have 6 layers, it will not add any new layers. It arranges
only the layers that exist.
layarrange row:=2 col:=3;
178
Graphing
The layswap X-Function is used to swap the location/position of two graph layers. You can reference
the layers by name or number.
The following example will swap the position on the page of layers indexed 1 and 2.
layswap igl1:=1 igl2:=2;
The following example will swap the position on the page of layers named Layer1 and Layer2.
layswap igl1:=Layer1 igl2:=Layer2;
Layers can be renamed from both the Layer Management tool as well as the Plot
Details dialog. In the Layer Management tool, you can double-click on the Name in the
Layer Selection list, to rename. In the left-hand navigation panel of the Plot Details
dialog, you can slow double-click a layer name to rename.
To rename from LabTalk, use layern.name$ where n is the layer index. For example,
to rename layer index 1 to Power, use the following: layer1.name$="Power";
179
LabTalk Scripting Guide
A label is one type of graphic object and can be created using the Label command. If no name is
specified when creating labels by the label -n command, Origin will name the labels automatically
with "Textn", where n is the creation index.
When creating labels, you can use escape sequences in a string to customize the text display. These
sequences begin with the backslash character (\). Enter the following script to see how these escape
sequences work. When there are spaces or multiple lines in your label text, quote the text with a
double quote mark.
label "You can use \b(Bold Text)
Subscripts and Superscripts like X\=(\i(i), 2)
\i(Italic Text)
\ab(Text with Overbar)
or \c4(Color Text) in your Labels";
The following script creates a new text label on your active graph window with the value from column
1, row 5 of sheet1 in book3. It works for both string and numeric.
label -s %([book3]Sheet1,1,5);
The following script creates a new text label on your active graph window from the value in row 1 of
column 2 of sheet2 in book1. Note the difference from the above example - the cell(i,j) function takes
row number as first argument. It works for a numeric cell only.
label -s $([book1]Sheet2!cell(1,2));
Besides, you can address worksheet cell values as your label contents. The following script creates a
new text label on your active graph window from the value in row 1 of column 2 of sheet2 in book1.
The value is displayed with 4 significant digits.
label -s $([book1]Sheet2!cell(1,2), *4);
The %( ) notation does not allow formatting and displays the value with full precision.
You need to use $( ) notation if you wish to format the numeric value.
To view the object name of any graphical object right-click on it and select
Programming Control from the context menu.
To update or reconstruct the graph legend, use the legendupdate X-function, which has the following
syntax:
legendupdate [mode:=optionName]
The square brackets indicate that mode is optional, such that legendupdate may be used on its
own, as in:
legendupdate;
which will use the default legend setting (short name) or use mode to specify what you would like
displayed:
legendupdate mode:=0;
which will display the Comment field in the regenerated legend for the column of data plotted. All
possible modes can be found in Help: X-Functions: legendupdate:
Note that either the index or the name of the mode may be used in the X-function call, such that the
script lines,
180
Graphing
legendupdate mode:=comment;
legendupdate mode:=0;
are equivalent and produce the same result.
The custom legend option requires an additional argument, demonstrated here:
legendupdate mode:=custom custom:=@WS;
All available custom legend options are given in the Text Label Options.
The following example shows how to use these functions and commands to update legends.
// Import sample data;
newbook;
string fn$ = system.path.program$ +
"Samples\Curve Fitting\Enzyme.dat";
impasc fname:=fn$;
string bn$ = %H;
// Create a two panels graph
newpanel 1 2;
// Add dataplot to layers
for (ii=1; ii<=2; ii++)
{
plotxy iy:=[bn$]1!wcol(ii+1) plot:=201 ogl:=$(ii);
}
// Upate whole page legends by worksheet comment + unit
legendupdate dest:=0 update:=0 mode:=custom custom:=@ln;
// Modify the legend settings for each layers
doc -e LW {
// Set legend font size
legend.fsize = 28;
// Set legend font color
legend.color = color(blue);
// Move legend to upper-left of the layer
legend.x = layer.x.from + legend.dx / 2;
legend.y = layer.y.to - legend.dy / 2;
};
Note: To modify the text of the legend, you can also use the label command. One reason to use this
would be if you wanted to display more than one text entry for each dataplot. The script below will
update the legend text to display both the worksheet name and the X column's Comment:
label -sl -n legend "\l(1) %(1, @WS) %(1X, @LC)";
181
LabTalk Scripting Guide
Notes: The pixel of a page can be found from the Print/Dimensions tab of Plot Details dialog.
For example:
win -T Plot; // Create an empty graph
// Create a text object at the layer center,
// named as "MyText", and the context is "Hello World"
label -p 50 50 -n MyText Hello World;
sec -p 1;
// Place the label at (1, 5)
MyText.x1 = 1;
MyText.y1 = 5;
182
Graphing
label -ra objectNamePrefix Delete all objects whose names start with objectNamePrefix
label -rc objectName Remove specified object, with the connected objects
183
10 Importing
10.1 Importing
Importing Data
Importing Images
Origin provides a collection of X-Functions for importing data from various file formats such as ASCII,
CSV, Excel, National Instruments DIAdem, pCLAMP, and many others. The X-Function for each file
format provides options relevant to that format in addition to common settings such as assigning the
name of the import file to the book or sheet name.
All X-Functions pertaining to importing have names that start with the letters imp. The table below
provides a listing of these X-Functions. As with all X-Functions, help-file information is available at
Script or Command line by entering the name of the X-Function with the -h option. For instance:
entering impasc -h in the Script window will display the help file immediately below the command.
Name Brief Description
Import EarthProbe (EPA) file. Now only EPA file is supported for EarthProbe
impEP
data.
185
LabTalk Scripting Guide
impJNB Import SigmaPlot (JNB) file. It supports version lower than SigmaPlot 8.0.
Import ETAS INCA MDF (DAT, MDF) files. It supports INCA 5.4 (file version
impMDF
3.0).
Import Minitab file (MTW) or project (MPJ). It supports the version prior to
impMNTB
Minitab 13.
impNetCDF Import netCDF file. It supports the file version lower than 3.1.
Import National Instruments TDM and TDMS files(TDMS does not support
impNITDM
data/time format)
Import pCLAMP file. It supports pClamp 9 (ABF 1.8 file format) and pClamp 10
imppClamp
(ABF 2.0 file format).
impSPE Import Princeton Instruments (SPE) file. It supports the version prior to 2.5.
186
Importing
This example imports an ASCII file (in this case having a *.txt extension) into the active worksheet or
matrix. Another X-Function, findfiles, is used to find a specific file in a directory (assigned to the
string path$) that contains many other files. The output of the findfiles X-Function is a string variable
containing the desired filename(s), and is assigned, by default, to a variable named fname$. Not
coincidentally, the default input argument for the impASC X-Function is a string variable called
fname$.
string path$ = system.path.program$ + "Samples\Import and Export\";
findfiles ext:=matrix_data_with_xy.txt;
impASC;
187
LabTalk Scripting Guide
188
Importing
Read the sql string and the connection string contained in a database query in
dbInfo
a worksheet.
189
LabTalk Scripting Guide
190
Importing
191
11 Exporting
11.1 Exporting
Exporting Worksheets
Exporting Graphs
Exporting Matrices
Exporting Videos
Origin provides a collection of X-Functions for exporting data, graphs, and images. All X-Functions
pertaining to exporting have names that start with the letters exp. The table below provides a listing
of these X-Functions. As with all X-Functions, help-file information is available at Script or Command
line by entering the name of the X-Function with the -h option. For instance: entering expgraph -h in
the Script window will display the help file immediately below the command.
Name Brief Description
expNITDM Export workbook data as National Instruments TDM and TDMS files
193
LabTalk Scripting Guide
1=text:Text File(*.txt),
2=csv:*.csv,
3=all:All Files(*.*)
194
Exporting
Export a graph as an image using the expGraph X-Function. The image size options are stored in
the nodes of tree variable named tr1, while resolution options (for all raster type images) are stored in
a tree named tr2.
One common application is to export a graph to a desired image format specifying both the width of
the image and the resolution. For example, consider a journal that requires, for a two-column article,
that graphs be sent as high-resolution (1200 DPI), *.tif files that are 3.2 inches wide:
// Export the active graph window to D:\TestImages\TEST.TIF.
// Width = 3.2 in, Resolution = 1200 DPI
1 = cm
2 = pixel
3 = page ratio
Note: this is a good example of accessing data stored in a tree structure to specify a particular type of
output. The full documentation for tr1 can be found in the online and product (CHM) help.
195
LabTalk Scripting Guide
label -r ForPrintOnly;
196
Exporting
197
LabTalk Scripting Guide
The following script shows a complete example of generating a video file "example.avi" in the user
files folder with a newly created empty graph window.
int err = vw.Create(%Y\example.avi);
//Write existing graphs into the video if the video can be created.
if(0 == err)
{
//Create an empty graph window with default template
win -t plot;
vw.WriteGraph( );
}
//Release the video writer
vw.Release( );
The vw.Release( ) method also has a return value. If it is 0 then the video generation is successful; if
it is 1, it indicates that the video generation failed.
198
12 The Origin Project
The Origin Project contains all of your data, operations, graphs, and reports. This chapter
discusses techniques for managing the elements of your project using script, and is presented in
the following sections:
Accessing Metadata
Internally, Origin updates a property that indicates when a project has been modified. Attempting to
Open a project when the current project has been modified normally triggers a prompt to Save the
current project. The document command has options to control this property.
199
LabTalk Scripting Guide
200
The Origin Project
The following X-Functions provide DOS-like commands to create, delete and navigate through the
subfolders of the project:
Name Brief Description
In this example :
doc -s; // Clear Origin's 'dirty' flag
doc -n; // Start a new project
pe_cd /; // Go to the top level
pe_mkdir "Test Subjects"; // Create a folder
pe_cd "Test Subjects"; // Navigate to that folder
pe_mkdir "Trials"; // Create a sub-folder
pe_mkdir "Results"; // and another
pe_cd /; // Return to the top level
pe_mkdir "Control Subjects"; // Create another folder
pe_cd "Control Subjects"; // Navigate to that folder
pe_mkdir "Trials"; // Create a sub-folder
pe_mkdir "Results"; // and another
pe_cd /; // Return to the top level
pe_mkdir "Comparison"; // Create a folder
201
LabTalk Scripting Guide
Note that if you have Open in Subfolder enabled in Tools : Options : [Open/Close] then you will have
an additional folder named Folder1.
202
The Origin Project
Note: For Origin 8.0, LabTalk variables took precedence over Column Label Row characters, for
example:
int L = 4; // For Origin 8.0 and earlier ...
Col(B)[L]$= // Returns the value in row 4 of Col(B), as a string
But for Origin 8.1, this has been changed so that the column label rows (L, U, C, etc.) will take
precedence:
int L = 4; // For Origin 8.1 ...
Col(B)[L]$= // Returns the Long Name of Col(B), as a string
The following example shows how to create and access user parameter rows
// Show the first user parameter row
wks.userParam1 = 1;
// Assign the 1st user parameter row a custom name
wks.userParam1$ = "Temperature";
// Write to a specific user parameter row of a column
col(2)[Temperature]$ = "96.8";
// Get a user-defined parameter row value
double temp = %(col(2)[Temperature]$);
To see a Sampling Interval header, you can try the following steps:
2. Right-click at the top of the remaining column (i.e., B(Y)), such that then entire
column is selected, and select Set Sampling Interval from the drop-down
203
LabTalk Scripting Guide
menu.
4. Click OK, and you will see a new header row created which lists the values you
specified.
The next example demonstrates how to do this from script, using X-functions.
Also, when you import certain types of data, e.g. *.wav, the sampling interval will show
as a header row.
The numeric values wks.col1.xinit and wks.col1.xinc will each have a value of 1,
12.3.3 Trees
Trees are a data type supported by LabTalk, and we also consider trees a form of metadata since
they give structure to existing data. They were briefly introduced in the section dealing with Data
Types and Variables, but appear again because of their importance to X-functions.
Many X-functions input and output data in tree form. And since X-functions are one of the primary
tools accessible from LabTalk script, it is important to recognize and use tree variables effectively.
204
The Origin Project
dDate = page.info.system.import.filedate;
// Both % and $ substitution methods are used
ty File %(strPath$)%(strName$), dated $(dDate,D10);
This tree structure includes a tree with additional information about the import. This tree can be
extracted as a tree variable using an X-Function:
Tree MyFiles;
impinfo ipg:=[Book2] tr:=MyFiles;
MyFiles.=; // Dump the contents of the tree to the script Window
Note: The contents of the impinfo tree will depend on the function used to import.
If you import multiple files into one workbook (using either New Sheets, New Columns or New Rows)
then you need to load a particular tree for each file as the Organizer only displays the system
metadata from the last import:
Tree trFile;
int iNumFiles;
// Use the function first to find the number of files
impinfo trInfo:=trFile fcount:=iNumFiles;
// Now loop through all files - these are indexed from 0
for( idx = 0 ; idx < iNumFiles ; idx++ )
{
// Get the tree for the next file
impinfo findex:=idx trInfo:=trFile;
string strFileName, strLocation;
//
strFileName$ = trFile.Info.FileName$;
strLocation$ = trFile.Info.DataRange$;
ty File %(strFileName$) was imported into %(strLocation$);
}
205
LabTalk Scripting Guide
Information can be stored in a workbook, matrix book or graph page using a tree structure. The
following example shows how to create a section and add subsections and values to the active page
storage area.
// Add a new section named Experiment
page.tree.add(Experiment);
// Add a sub section called Sample;
page.tree.experiment.addsection(Sample);
// Add values to subsection;
page.tree.experiment.sample.RunNumber = 45;
page.tree.experiment.sample.Temperature = 273.8;
// Add another subsection called Detector;
page.tree.experiment.addsection(Detector);
// Add values;
page.tree.experiment.detector.Type$ = "InGaAs";
page.tree.experiment.detector.Cooling$ = "Liquid Nitrogen";
Once the information has been stored, it can be retrieved by simply dumping the storage contents:
// Dump entire contents of page storage
page.tree.=;
// or programmaticaly accessed
temperature = page.tree.experiment.sample.temperature;
string type$ = page.tree.experiment.detector.Type$;
ty Using %(type$) at $(temperature)K;
You can view such trees in the page Organizer for Workbooks and Matrixbooks.
206
The Origin Project
207
LabTalk Scripting Guide
The workbook in each Freq folder contains three columns including DataX, DataY and the frequency,
which is a constant. The workbook's name in the Bgsignal folder is Bgsig. In the Bgsig workbook,
there are three columns including DataX and two Y columns whose long names correspond to set
frequencies in the workbook in each Freq folder.
The aim is to add a column in each workbook and subtract the background signal for a particular
frequency from the sample data for the same frequency. The following Labtalk script performs this
operation.
doc -e LB
{ //Loop over each worksheet.
if(%H != "Bgsig") //Skip the background signal workbook.
{
Freq=col(3)[1]; //Get the frequency.
wks.ncols=wks.ncols+1; //Add a column in the sample sheet.
//bg signal column for Freq using long name.
range aa=[Bgsig]1!col("$(Freq)");
wcol(wks.ncols)=col(2)-aa; //Subtract the bg signal.
wcol(wks.ncols)[L]$="Remove bg signal"; //Set the long name.
}
}
For increased control, you may also loop through the books and then loop through the sheets in your
code, albeit a bit more slowly than the code above.
The following example shows how to loop over all workbooks in the current/active Project Explorer
Folder, and then loop over each sheet inside each book that is found:
int nbooks = 0;
// Get the name of this folder
string strPath;
pe_path path:=strPath;
// Loop over all Workbooks ...
// Restricted to the current Project Explorer Folder View
doc -ef W {
int nsheets = 0;
// Loop over all worksheets in each workbook
doc -e LW {
type Sheet name: %(layer.name$);
nsheets++;
}
type Found $(nsheets) sheet(s) in %H;
type %(CRLF);
nbooks++;
}
type Found $(nbooks) book(s) in folder %(strPath$) of project %G;
Additionally, we can replace the internal loop using Workbook properties:
int nbooks = 0;
// Get the name of this folder
string strPath;
pe_path path:=strPath;
// Loop over all Workbooks ...
// Restricted to the current Project Explorer Folder View
doc -ef W {
// Loop over all worksheets in each workbook
loop(ii,1,page.nlayers) {
range rW = [Book1]$(ii)!;
type Sheet name: %(rw.name$);
}
type Found $(page.nlayers) sheet(s) in %H;
208
The Origin Project
type %(CRLF);
nbooks++;
}
// Final report - %G contains the project name
type Found $(nbooks) book(s) in folder %(strPath$) of project %G;
209
LabTalk Scripting Guide
210
The Origin Project
the OPJ. This method is accessible both from the GUI and from LabTalk script.
You can add an Admin password to the project and prevent unauthorized editing of the OPJ.
This method does not restrict access to the OPJ; nor does it prevent a user from editing and
saving the OPJ to a new file name. This method is LabTalk script-accessible only.
doc -pwd
This opens the Password dialog where you can set or change the project password.
For GUI access to this feature, click Tools: Protection: Protect Project and enter a password.
211
LabTalk Scripting Guide
As indicated by the square brackets, choosing a password is optional. If you do not choose a
password, you will not be required to supply one when logging into Admin mode.
Once you have created a password, or accepted the default ("origin"), log into Admin mode by
entering the following at the command line:
doc -pw [password] // log into Admin Mode. If password was specifed, give
password
Additional commands:
doc -pwx // logout of Admin Mode. No access to protections
doc -pwr // remove password. Must be logged in to execute
doc -pwta // list all books & sheets with protections enabled
For complete documentation on the document command see the document command.
Admin mode enabled for OPJ but user is not logged in as Admin.
Modified file
The asterisk indicates that the OPJ has been modified, but you will not be able to save the OPJ
unless you log in before saving. You can exit the OPJ without saving and without logging in.
212
The Origin Project
There is a general inheritance rule on protection flags: Once you set protection on a book, then all
sheets inside the book will inherent the flags from the book. The exception to this rule is the Delete
flag. You must separately control book and sheet deletion flags (i.e. You may not want to allow book
deletion, but still allow deletion of individual sheets).
2 Data: Include all the cells in a worksheet, data cells or label cells.
Structure: Keep the columns in the sheet unchanged. Prevent insert/delete columns
80
or moving columns, but allow rows to be changed.
100 Rename: Prevent changing sheet name (not supported for workbook).
Note: Before applying protections, please read the note on Exclusion Zones.
lay -lw hex(82); //set active sheet to protect data and structure
lay -lw; //protect everything
lay -lw 2; //protect only data
lay -lw hex(180); //no insert/del cols/rows, no sheet rename
lay -lw 0; //remove all protections on the current sheet
... where hex value is derived from values in the above table.
page -lw; //lock book and all sheets, no changes, cannot delete book or
sheets
page -lw hex(482); //lock delete, structure change and data edit
213
LabTalk Scripting Guide
For complete documentation on the page command see the page command.
layer -les n
... where n can be one of the following:
Value Description
Add the current selection, one range or multiple via CTRL+select, as new Exclusion
1
Zones.
Note: You can only make Exclusion Zone modifications when the sheet is unprotected. To set the
sheet up as a form, you should (1) add all the needed Exclusion Zones, then (2) protect the sheet
from modification with lay -lw
214
The Origin Project
The following script sets up a workbook with a locked data sheet and protects the workbook from
deletion. The OPJ can then be saved and shared with others who can view, graph, and analyze the
data, but cannot edit or delete.
Analysis results are output to additional sheets, so routines that generate output such as Smooth
should be configured to send output to another sheet, as the data sheet in this example will be
protected from modifications.
// Import a sample file
newbook;
string fname$=system.path.program$+"Samples\Curve Fitting\Gaussian.dat";
impasc;
// Set password and login - change mypwd to your desired password string
doc -pwa mypwd;
doc -pw mypwd;
// Protect data sheet structure, prevent editing, deleting
lay -lw hex(482);
// Protect page from deletion
page -lw hex(400);
// logout
doc -pwx;
// Now you can save the OPJ and others can view data, graph, and also analyze
// Analysis results can go into new sheets, not new cols in same sheet
215
13 Analysis and Applications
LT Mathematics
LT Statistics
LT Curve Fitting
Signal Processing
Image Processing
13.2 Mathematics
13.2.1 Mathematics
In this section we feature examples of four common mathematical tasks in data processing:
Differentiation
Integration
217
LabTalk Scripting Guide
Interpolation
13.2.3 Differentiation
13.2.3.1 Finding the Derivative
The following example shows how to calculate the derivative of a dataset. Note that the differentiate
X-Function is used, and that it allows higer-order derivatives as well:
// Import the data
newbook;
fname$ = system.path.program$ + "\Samples\Spectroscopy\HiddenPeaks.dat";
impasc;
218
Analysis and Applications
The differentiate X-Function also allows you to obtain the derivatives using Savitsky-Golay
smoothing. If you want to use this capability, set the smooth variable to 1. Then you can customize
the smoothing by specifying the polynomial order and the points of window used in the Savitzky-
Golay smoothing method. The example below illustrates this.
// Import a sample data with noise
newbook;
fpath$ = "\Samples\Signal Processing\fftfilter1.DAT";
fname$ = system.path.program$ + fpath$;
impasc;
bkname$=%h;
13.2.4 Integration
The integ1 X-Function is capable of finding the area under a curve using integration. Both
mathematical and absolute areas can be computed. In the following example, the absolute area is
calculated:
//Import a sample data
newbook;
fname$ = system.path.program$ + "Samples\Mathematics\Sine Curve.dat";
impasc;
//Calculate the absolute area of the curve and plot the integral curve
integ1 iy:=col(2) type:=abs plot:=1;
Once the integration is performed, the results can be obtained from the integ1 tree variable:
// Dump the integ1 tree
integ1.=;
// Get a specific value
double area = integ1.area;
The X-Function also allows specifying variable names for quantities of interest, such as:
double myarea, ymax, xmax;
integ1 iy:=col(2) type:=abs plot:=1 area:=myarea y0:=ymax x0:=xmax;
type "area=$(myarea) %(CRLF)ymax=$(ymax) %(CRLF)xmax=$(xmax)";
Integration of two-dimensional data in a matrix can also be performed using the integ2 X-Function.
This X-Function computes the volume beneath the surface defined by the matrix, with respect to the
z=0 plane.
// Perform volume integration of 1st matrix object in first matrix sheet
range rmat=[MBook1]1!1;
integ2 im:=rmat integral:=myresult;
type "Volume integration result: $(myresult)";
13.2.5 Interpolation
Interpolation is one of the more common mathematical functions performed on data, and Origin
supports interpolation in two ways: (1) interpolation of single values and datasets through range
notation and (2) interpolation of entire curves by X-Functions.
219
LabTalk Scripting Guide
The following examples show how to perform interpolation using range as function, with data from a
worksheet as the argument.
Example1: The following code illustrates the usage of the various smoothing parameters for bspline:
col(1)=data(1,9); // Fill column 1 with row data
col(2)=normal(9); // Fill column 2 with random values
col(3)=data(1,9,0.01); // Fill Col(3) with desired X values
wks.col3.type = 4;
range bb=(1,2); // Declare range using cols 1,2;
// Compute interpolated values using different parameter settings
loop(i, 4, 10) {
wcol(i)=bb(col(3), bspline, $(i*0.1));
}
Example2: With an XY range, new Y values can be obtained at any X value using code such as:
// Generate some data
newbook;
wcol(1)={1, 2, 3, 4};
wcol(2)={2, 3, 5, 6};
// Define XYrange
range rr =(1,2);
// Find Y value by linear interpolation at a specified X value.
rr(1.23) = ; // ANS: rr(1.23)=2.23
220
Analysis and Applications
From Graph
You can also use range interpolation when a graph page is active.
Example 1: Interpolate an array of values.
// Define range on active plot:
range rg = %C;
// Interpolate for a scalar value using the line connection style:
rg(3.54)=;
// Interpolate for an array of values:
// Give the location of the new X values:
range newX = [Book2]1!1;
// Give the location where the new Y values (output) should go:
range newY = [Book2]1!2;
// Compute the new Y values:
newY = rg(newX);
Example 2: Specify the interpolation method.
// Define range on specific plot:
range -wx rWx = 2; // Use X of 2nd plot in active layer
range -w rWy = 2; // Use Y of 2nd plot in active layer
range rr = (rWx,rWy); // Construct an XY range from two ranges
// Give the location where the new X values (output) should go:
range newX = [Book2]1!1;
newX = {5,15,25};
range newY1 = [Book2]1!2; // Range for new Y
range newY2 = [Book2]1!3; // Range for new Y
// Find new Y values by linear interpolation for an array of X values:
newY1 = rr(newX);
// Find new Y values by bspline interpolation for an array of X values:
newY2 = rr(newX,bspline);
221
LabTalk Scripting Guide
For two arbitrary datasets with the same length, where both are increasing or decreasing, Origin
allows you to interpolate from one dataset to the other at a given value. The datasets can be a range
variable, dataset variable, or column. The form to perform such interpolation is:
dataset1(value, dataset2)
which will perform interpolation on the group of XY data constructed by dataset2 and dataset1, and it
will return the so-called Y (dataset1) value at the given so-called X (dataset2) value. For example:
// Using datasets
dataset ds1 = {1, 2, 3, 4};
dataset ds2 = {2, 3, 5, 6};
// Return interpolated value in ds2 where X in ds1 is 1.23
ds2(1.23, ds1) = ; // Return 2.23
// Return interpolated value in ds1 where X in ds2 is 5.28
ds1(5.28, ds2) = ; // Return 3.28
// Using ranges
newbook;
wks.ncols = 3;
range r1 = 2; // Column 2 in active worksheet
r1 = {1, 2, 3, 4};
range r2 = 3; // Column 3 in active worksheet;
r2 = {2, 3, 5, 6};
r2(1.23, r1) = ;
r1(5.28, r2) = ;
// Using columns
col(3)(1.23, col(2)) = ;
col(2)(5.28, col(3)) = ;
Origin provides three X-Functions for interpolating XY data and creating a new output XY data pair:
Name Brief Description
The following example shows how to use an existing X dataset to find interpolated Y values:
// Create a new workbook with specific column designations
newbook sheet:=0;
newsheet cols:=4 xy:="XYXY";
// Import a sample data file
fname$ = system.path.program$ + "Samples\Mathematics\Interpolation.dat";
impasc;
222
Analysis and Applications
// Interpolate the data in col(1) and col(2) with the X values in col(3)
range rResult=col(4);
interp1 ix:=col(3) iy:=(col(1), col(2)) method:=linear ox:=rResult;
The following example performs trace interpolation on data where X is not monotonic:
//Create a new workbook and import the data file
fname$ = system.path.program$ + "Samples\Mathematics\circle.dat";
newbook;
impasc;
223
LabTalk Scripting Guide
13.3 Statistics
13.3.1 Statistics
This is an example-based section demonstrating support for several types of statistical tests
implemented in script through X-Function calls.
Descriptive statistics
Hypothesis Testing
Nonparametric Tests
Survival Analysis
corrcoef
Correlation Coefficient
(Pro Only)
mstats
Compute descriptive statistics on a matrix
(Pro Only)
stats Treat selected columns as a complete dataset; compute statistics of the dataset.
For a full description of each of these X-Functions and its inputs and outputs, please see the
Descriptive Statistics.
224
Analysis and Applications
The colstats X-Function can perform statistics on columns. By default, it outputs the mean, the
standard deviation, the number of data points and the median of each input column. But you can
customize the output by assigning different values to the variables. In the following example, colstats
is used to calculate the means, the standard deviations, the standard errors of the means, and the
medians of four columns.
//Import a sample data with four columns
newbook;
fname$ = system.path.program$ + "Samples\Statistics\nitrogen_raw.txt";
impasc;
//Correlation Coefficient
225
LabTalk Scripting Guide
rowttest2 (Pro
Perform a two-sample t-test on rows.
Only)
Determine whether two sample means are equal in the case that they are
ttestpair
matched.
vartest1
Determine whether the sample variance is equal to a specified value.
(Pro Only)
vartest2
Determine whether two sample variances are equal.
(Pro Only)
For a full description of these X-functions, including input and output arguments, please see the
Hypothesis Testing.
//Normality test
swtest irng:=col(a) prob:=p1;
if (p1 < 0.05)
{
type "The sample is not likely to follow a normal distribution."
}
else
{
// Test whether the mean is 21
ttest1 irng:=col(1) mean:=21 tail:=two prob:=p2;
if (p2 < 0.05) {
type "At the 0.05 level, the population mean is";
type "significantly different from 21."; }
else {
type "At the 0.05 level, the population mean is NOT";
type "significantly different from 21."; }
}
226
Analysis and Applications
227
LabTalk Scripting Guide
X-Function vartest1 is used to perform a chi-squared variance test, so to determine whether the
sample from a normal distribution could have a given hypothetical vaiance value. The following
example will perform one-sample test for variance, and output the P-value.
// Import sample data
newbook;
string fpath$ = "Samples\Statistics\vartest1.dat";
string fname$ = system.path.program$ + fpath$;
impasc;
// Perform F-test
// Tail is two tailed
// Test variance is 2.0
// P-value stored in variable p
vartest1 irng:=col(1) var:=2.0 tail:=two prob:=p;
// Ouput P-value
p = ;
// Perform F-test
// And Tail is upper tailed
vartest2 irng:=(col(1), col(2)) tail:=upper;
Test whether or not the medians of the paired populations are equal.
signrank2/sign2
Input data should be in raw format.
Test whether the two samples have identical distribution. Input data
mwtest/kstest2
should be Indexed.
kwanova/mediantest Test whether different samples' medians are equal, Input data should be
228
Analysis and Applications
getresults tr:=mynw;
229
LabTalk Scripting Guide
function, and supports three methods for testing the equality of the survival function: Log Rank,
Breslow and Tarone-Ware.
As an example, scientists are looking for a better medicine for cancer resistance. After exposing
some rats to carcinogen DMBA, they apply different medicine to two different groups of rats and
record their survival status for the first 60 hours. They wish to quantify the difference in survival rates
between the two medicines.
// Import sample data
newbook;
fname$ = system.path.program$ + "Samples\Statistics\SurvivedRats.dat";
impasc;
}
else
{
type "The two medicines are not significantly different.";
}
230
Analysis and Applications
page.active$="ColorectalCarcinoma";
loop(ii, 1, 7)
{
// If probability is less than 0.05,
// we can say it is effective for survival time.
if (cox.paramestim.param$(ii).prob<=0.05)
type wks.col$(ii+2).comment$;
}
Non-linear Fitting
In LabTalk scripts, three simple quick use X-Functions, fitLR, fitPoly, and fitMR, are available for
performing linear regression, polynomial regression, and multiple linear regression, respectively. And
the -h switch can be used to see the argument list.
231
LabTalk Scripting Guide
// file name
string strFile$ = system.path.program$ + "Samples\Curve Fitting\Linear
Fit.dat";
impasc fname:=strFile$; // import the data
// perform linear fit on the first ten points of column 1 (X) and column 2
(Y)
// and the fitted data is output to FitData column
fitLR iy:=(1,2) N:=10 oy:=col(FitData);
// a tree object named fitLR is created, and contains the output values
fitLR.a = ; // output the fitted intercept
fitLR.b = ; // output the fitted slope
fitLR.= ; // output all the results, which include fitted intercept and
slope
More examples about linear regression can be found in Curve Fitting sample page, or under Fitting
category in XF Script Dialog (press F11 to open).
// file name
string strFile$ = system.path.program$ + "Samples\Curve Fitting\Polynomial
Fit.dat";
impasc fname:=strFile$; // import data
wks.addcol(PolyCoef); // add a new column for polynomial coefficients
wks.addcol(FittedX); // add a new column for fitted X values
wks.addcol(FittedY); // add a new column for fitted Y values
232
Analysis and Applications
// perform linear fit and generate a report with the prepared GUI tree
xop execute:=report iotrgui:=lrGUI;
parameters.
Besides nlbegin, you can also start a fitting process according to your fitting model or data by the
following X-Functions:
nlbeginr: Fitting multiple dependnet/independent variables' model
233
LabTalk Scripting Guide
Start a LabTalk nlfit session on worksheet data. It is used for fitting multiple
nlbeginr
dependent/independent variables functions.
nlbeginm Start a LabTalk nlfit session on matrix data from matrix object or graph
234
Analysis and Applications
nlbeginz Start a LabTalk nlfit session on XYZ data from worksheet or graph
nlpara Open the Parameter dialog for GUI editing of parameter values and bounds
For a full description of each of these X-functions and its inputs and outputs, please see the X-
function Reference.
13.5.1 Smoothing
Smoothing noisy data can be performed by using the smooth X-Function.
// Smooth the XY data in columns 1,2 of the worksheet
// using SavitzkyGolay method with a third order polynomial
range r=(1,2); // assume worksheet active with XY data
smooth iy:=r meth:=sg poly:=3;
To smooth all plots in a layer, you can loop over the plots as below:
// Count the number of data plots in the layer and save result in
//variable "count"
layer -c;
// Get the name of this Graph page
string gname$ = %H;
// Create a new book named smooth - actual name is stored in bkname$
235
LabTalk Scripting Guide
newbook na:=Smoothed;
// Start with no columns
wks.ncols=0;
loop(ii,1,count) {
// Input Range refers to 'ii'th plot
range riy = [gname$]!$(ii);
// Output Range refers to two, new columns
range roy = [bkname$]!($(ii*2-1),$(ii*2));
// Savitsky-Golay smoothing using third order polynomial
smooth iy:=riy meth:=sg poly:=3 oy:=roy;
}
// Set data type to complex prior to store complex results from FFT analysis
wks.col3.numerictype = 11;
col(C)[L]$ = "FFT Complex";
col(D)[L]$ = "Frequency";
wks.col4.type = 4; //Set X column type
col(E)[L]$ = "Magnitude";
col(F)[L]$ = "Phase";
col(F) = fftphase(col(C)); // Use fftphase(col(C), 2, 1, 0) to obtain Two-
sided, unwrapped phase with radian unit
wks.col7.numerictype = 11;
col(G)[L]$ = "Shifted FFT Complex";
col(G) = fftshift(col(C));
236
Analysis and Applications
col(D)[L]$ = "Amplitude";
col(D) = fftamp( fftc(col(C)) ); //Without Origin window correction
The following example shows how to perform fft analysis on multiple columns using loop and arrange
obtained amplitude and phase columns side by side. You can also calculate FFT results for multiple
columns directly on worksheet by selecting multiple columns on the worksheet, and right click to
select Set Multiple Columns Values....
//Prepare multiple column data for FFT analysis
newbook;
int nc = 5, ii;
wks.ncols = 4*nc+2;
//Fill x column with time data
col(A) = data(0, 1-1e-3, 1e-3);
//Fill five columns with sum of an f1 Hz sinusoid and an f2 Hz sinusoid
for( ii = 1; ii<=nc; ii++ )
{
double f1, f2;
f1 = 50 + 20*ii;
f2 = 100 + 20*ii;
wcol(ii+1)[L]$ = "Data$(ii)";
wcol(ii+1) = (2+ii)*sin(2*pi*f1*col(A))+(8-ii)*sin(2*pi*f2*col(A))+rnd();
}
237
LabTalk Scripting Guide
//Plot FFT amplitude and phase results for five columns in two layers
plotstack iy:=($(2*nc+2),$(2*nc+3):$(4*nc+2)) portrait:=0 order:=0 layer:=2
number:="5 5";
238
Analysis and Applications
For peaks that do not require baseline treatment or other advanced options, you can
also use peak functions to perform nonlinear fitting. For more information on non-
linear fitting from script, please see the Curve Fitting section.
239
LabTalk Scripting Guide
240
Analysis and Applications
This example rotates, trims the margins, and applies an auto-level to make the image more compact
and clear.,
imgRotate angle:=42;
imgTrim t:=17;
matrix -pg DIM nCol2 nRow2; //Get the dimension of the modified iamge
//Report
window -n n Report;
old = type.redirection;
type.redirection = 2;
type.notes$=Report;
type "Dimension of the original image: ";
type " $(nCol1) * $(nRow1)\r\n"; // "754 * 668"
type "Dimension of the modified image: "; // "688 * 601"
type " $(nCol2) * $(nRow2)\r\n";
type.redirection = old;
241
LabTalk Scripting Guide
We can also rotate, resize, and adjust the color scale of the image in new image window.
Minimum Origin Version Required: 2016 SR0
fname$ = SYSTEM.PATH.PROGRAM$ + "Samples\Image Processing and
Analysis\Rice.bmp";
cvopen fname:=fname$; //open the image in new image window;
242
Analysis and Applications
//Edge detection
// the threshold value 12 used to determine edge pixels,
// and shv(Sobel horizontal & vertical) Edge detection filter is applied.
imgEdge t:=12 f:=shv;
edge$ = %h;
243
LabTalk Scripting Guide
//Apply pallete
fname$ = System.path.program$ + "palettes\Rainbow.PAL";
imgpalette palfile:=fname$;
cvGray img:=<active>;
cvPalette img:=<active> fname:="C:\Program
Files\OriginLab\Origin2016\Palettes\Lite Cyan.pal";
// Create a new matrix book and import all images as new sheets
newbook mat:=1;
impImage options.FirstMode:=0 options.Mode:=4;
// Loop over all sheets and convert image to byte data
doc -e LW {
img2m om:=<input> type:=1;
}
244
14 User Interaction
Bringing Up a Dialog
2. Single String
245
LabTalk Scripting Guide
selected, xpos will be assigned the value 0. If Cancel is selected, xpos will be assigned the value 0,
#Command Error! will be printed, and script execution will stop.
getyesno "Should X be positive?" xpos "Check Sign of X"
If additional script processing is required in any event, this command should be called from elsewhere
and the numeric value can be tested. In the following example, getyesno is called from its own
section of code and the two string inputs are passed as arguments to the section(note, a multi-section
LabTalk script will not work if simply pasted to the script window; save to file and run):
[Main]
// Here is the calling code
int iVal = -1;
run.section(,myGetYesNo,"Create a Graph of results?" "Graphing Option");
if( iVal > 0 )
{
type "Graph generated"; // Yes response
}
else
{
type "Graph NOT generated"; // No or Cancel response
}
// 'myGetYesNo' section
[myGetYesNo]
getyesno (%1) iVal (%2);
246
User Interaction
getn
(Value) nn
(Measurement Type) measurement$
(Units) units$
(Event Name) event$
(Dialog Title);
brings up the following dialog, prompting the user for input:
The values entered in this dialog will be assigned to the declared variables. If the variables have an
initial value (before GetN is called), that value will show up in the input box, otherwise the input box
will appear blank. In either case, the initial value can be changed or kept.
To check the data entered, run the following line of script:
// Output the data:
type In %(event$), the %(measurement$) was $(nn) %(units$);
This next example script assumes a Graph is the active window and prompts for information then
draws a line and labels it. The call to GetN uses string registers and pre-defined lists as inputs.
%A=Minimum;
iColor = 15;
dVal = 2.75;
iStyle = 2;
247
LabTalk Scripting Guide
The following character sequences, beginning with the @ character, access pre-defined lists for GetN
arguments:
List Description
@P Pattern List
@T Font List
Note that the value returned when a list item is selected within the GetN dialog is the index of the
item in the list. For instance, if one of your GetN entries is:
(Font Size) fs:@S
and you select 18 from the drop-down list in the dialog, the variable fs will hold the value 8, since 18
is the 8th item in the list.
Below is another example script that allows a user to change a Symbol Plot to a Line + Symbol Plot
or the reverse:
get %C -z iSymbolSize; // Get current Symbol Size
get %C -cl iLineColor; // Get current Line color
iUseLine = 0;
// Now open the dialog to the user
getn (Symbol Size) iSymbolSize
(Use Line) iUseLine:2s
(Line Color) iLineColor:@C
(Set Plot Style);
// If User asked for Line
if(iUseLine == 1)
{
set %C -l 1; // Turn on the line
set %C -cl iLineColor; // Set the line color
}
// .. if not
else
set %C -l 0; // Turn off line
set %C -z iSymbolSize; // Set Symbol size
248
User Interaction
249
LabTalk Scripting Guide
Pressing Enter key to select a point works more reliably than double-clicking on the
point.
You can also use the getpts command to gather data values from a graph.
250
User Interaction
List of Tools in Origin Tools Toolbar. Those in bold are useful in programming.
Tool
Description
Number
Pointer - The Pointer is the default condition for the mouse and makes the
0
mouse act as a selector.
3 Data Reader - Reads the location of a data point on a graph. (Graph only)
Data Selector - Sets a pair of Data Markers indicating a data range. (Graph
4
only)
251
LabTalk Scripting Guide
5 Draw Data - Allows user the draw data points on a graph. (Graph only)
ZoomOut - Zooms out (one level) when clicking anywhere in a graph. (Graph
16
only)
18 Regional Mask Tool - Allows masking a points in a data range. (Graph only)
252
User Interaction
253
15 Working with Excel
Origin can use Excel Workbooks directly within the Origin Workspace. The Excel Workbooks can be
stored within the project or linked to an external Excel file (*.xls, *.xlsx). An external Excel Workbook
which was opened in Origin can be converted to internal, and an Excel Workbook created within
Origin can be saved to an external Excel file.
To create a new Excel Workbook within Origin ..
window -tx;
The titlebar will include the text [Internal] to indicate the Excel Workbook will be saved in the Origin
Project file.
To open an external Excel file ..
document -append D:\Test1.xls;
The titlebar will include the file path and name to indicate the Excel file is saved external to the Origin
Project file.
You can save an internal Excel Workbook as an external file at which point it becomes a linked
external file ..
// The Excel window must be active. win -o can temporarily make it active
window -o Book5 {
// You must include the file path and the .xls extension
save -i D:\Test2.xls;
}
You can re-save an external Excel Workbook to a new location creating a new file and link leaving
the original file on disk ..
// Assume the Excel Workbook is active
// %X holds the path of an opened Origin Project file
save -i %XNewBook.xls;
255
16 Running R in Origin
commands within the Origin environment and transfer data between the two applications either
using a dialog interface, or by using commands. For examples, see Data Analysis in Origin
with R Console.
Using the LabTalk objects R and RS (RServe) . The R and RS LabTalk objects can execute R
To make use of the R object and R Console, you need to have R installed locally. To use the RS
object and the Rserve Console, you will need to have the R packages installed on the server side,
and communicate to the server computer with Origin on the client side.
For information on obtaining and installing R locally, see this topic.
16.1.1.1 Initialize R or RS
Before running R command in Labtalk, you can initialize the R application by running:
if( R.Init()<0 )
{
type -b "Please install R software first.";
return;
}
in the Script Window.
To initialize the RS object, please refer to Script below, and view this page for parameters setting.
if(RS.Init(***.***.**.**, 12306, user, password)<0) // Address is Rserve PC
IP, e.g: 192.168.18.75
{
type -b "Initialize failed.";
return;
}
257
LabTalk Scripting Guide
Execute R command
R.Exec(rand<-sample(x = 1:6, size = 50, replace = TRUE));
R.Exec(rand);
and perform analysis:
R.Exec(sum<-summary(rand));
R.Exec(sum);
The summary could be shown in this way:
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 2.00 3.50 3.56 5.00 6.00
Execute Multiple R Command Lines
R.Exec("array<-1:25;dim(array)<-c(5,5);array") // Run multiple R command
lines separated by semicolon
Execute RS command
string fname$ = system.path.program$ + "Samples\Curve Fitting\Sensor01.dat";
impasc;
range r1 = 1:2;
258
Running R in Origin
//Suppose there is a logical vector temp with value [1] FALSE FALSE TRUE
range rl=1;
R.Receive(%(rl),temp,0); // Column 1 in active sheet would be 0,0,1 instead
259
LabTalk Scripting Guide
16.2.1.1 R Object
//R object example to call R in LabTalk
//run.section(testRex,LogisticRoex)
int nc = wks.ncols;
wks.ncols = nc + 6;
260
Running R in Origin
16.2.1.2 RS Object
You need to Setup R Serve before running this example.
//RS example to call Rserve in LabTalk
//Import sample data
newbook;
string fn = system.path.program$ + "Samples\Statistics\LogRegData.dat";
impasc fname:=fn$ options.sparklines:=0;
261
LabTalk Scripting Guide
int nc = wks.ncols;
wks.ncols = nc + 6;
262
17 Working with Python
Origin provides embedded python environment, so that you can either run python in Origin (support
both command line and .py file), or use a PyOrigin module to access Origin from Python.
The embedded Python in Origin could be either version 3.3.5 or version 2.7.8. By default, it is Python
version 3.3 running in Origin. To switch to use Python version 2.7, open Script Window and select
menu Edit: Script Execution: Python 2.7. It can be also switched by a system variable @PYV.
When @PYV = 3 (Default), the embedded Python is 3.3.5, while if @PYV = 2, it is 2.7.8. To set value
for a system variable, click Tools:System Variables to open the Set System Variables dialog.
The following document page is written based on the assumption that Python 3.3.5 is used in Origin.
Minimum Origin Version Required: 2015 SR0
the Python command line and hit Enter key to directly execute the command.
OR
263
LabTalk Scripting Guide
Use the run -py command option switch in LabTalk, for example, make sure Edit:Script
run.python(myname='Origin';print(myname));
//Should output 'Origin'
To execute multiple Python commands or a Python module in the Script Window, set
the system variable @PYI to 0 to turn off interactive mode. Choose Tools:System
Variables to open the Set System Variables dialog, enter Variable = pyi and enter a
Value = 0.
// Define a string for the file path and name of the .py file
string str$ = system.PATH.PROGRAM$ + "\Samples\Python\ListMember.py";
// Run the .py file
run -pyf "%(str$)";
file.
OR
Use the run.python() object method in LabTalk, for example, make sure Edit:Script
264
Working with Python
run -pye 10 % 4;
// It also returns the evaluated value 2, which is the same as the example
above
265
LabTalk Scripting Guide
17.2.3.1 Run Python File and Send Data From Python to Origin
The Python file SendDataToWorksheet.py under <Origin EXE Folder>\Samples\Python is an
example to show how to send data from Python to Origin, it created a dialog using Python tkinter
module to get user input such as column format, number of rows, etc. Then these inputted
parameters will be passed to Origin.
In order to run this .py file, execute the following LabTalk script in the Script Window:
//Make sure the Script Execution Mode is LabTalk
//Make sure a worksheet is active in Origin
string str$ = system.PATH.PROGRAM$ +
"\Samples\Python\SendDataToWorksheet.py";
run -pyf "%(str$)";
To attach your Python files to an Origin project, right click on the Project folder and
select Add Files... to include your Python file(s).
266
Working with Python
The embedded Python in Origin includes all the basic modules and the modules which are installed
to your Python application. If you want to use other Python extensions, e.g. PyQt4, numpy, scipy,
follow the procedure below:
1. Make sure the downloaded Python extension version is either version 3.3 or version 2.7 to be
2. Make sure the downloaded Python extension corresponding to same CPU register size as the
Origin being running - 32 bit or 64 bit. To know whether current Origin verison is 32 bit or 64 bit,
you can directly read it from Origin program window title bar or type command " system.bits=;"
3. Make sure the installed Python extension path is properly appended so it can be directly used
4. Make sure current Python running version is compatible with downloaded Python extension. By
default, it is Python version 3.3 running in Origin. To switch to use Python version 2.7, open
Script Window and select menu Edit: Script Execution: Python 2.7.
If the Python extension is installed in default path, such as C:\Program Files (x86)\Python\Lib\site-
packages\, you can directly use the package as shown in example below:
# For Python extension version 3.3 (default)
import numpy
print(x)
Otherwise, you have to add its installation folder to the system path list before you import it. To add
the installation folder to system path list, the recommended approach is to run the following Python
statements in the embedded Python environment of Origin (either directly run statements, or run from
files):
import sys
py_ext_path = "C:\Python33\Lib\site-packages"
267
LabTalk Scripting Guide
For example purpose, you can click desired version folder and find the compatible
packages to download in links Numpy and Scipy.
268
18 Automation and Batch Processing
Analysis Templates
Batch Processing
269
LabTalk Scripting Guide
To learn how to create Analysis Templates, please refer to the Origin tutorial: Creating and Using
Analysis Templates.
2. Add an extra column to the data sheet, or to a new sheet in the same workbook.
3. Open the Set Column Values dialog from this newly added column.
4. Enter the desired analysis script in the Before Formula Scripts panel. Note that your script
5. In you script, make sure to reference at least one column or cell of your data sheet that will get
replaced with new data. You can do this by defining a range variable that points to a data
column and then use that range variable in your script for computing your custom analysis
output.
6. Set the Recalculate drop-down in the dialog to either Manual or Auto, and press OK.
7. Use the File: Save Workbook as Analysis Template... menu item to save the Analysis
Template.
For an example on setting up such a template using script, please refer to the Origin tutorial: Creating
Analysis Templates using Set Column Value.
270
Automation and Batch Processing
The following example shows how to import 10 files and perform a curve fit operation and print out
the fitting results:
// Find all files using wild card
string path$ = system.path.program$ + "Samples\Batch Processing"; // Path to
find files
// Find the files in the folder specified by path$ variable (default)
// The result file names are stored in the string variable fname$
// Separated by CRLF (default). Here wild card * is used, which means
// all files start with "T", and with the extension "csv"
findFiles ext:="T*.csv";
271
LabTalk Scripting Guide
page.active = 1;
impasc fname.GetToken(iFile, CRLF)$
}
paMultiY Perform peak analysis of multiple Y datasets using Peak Analyzer theme
The following script shows how to use the batchProcess X-Function to perform curve fitting of data
from 10 files using an analysis template, with a summary report created at the end of the process.
// Find all files using wild card
string path$ = system.path.program$ + "Samples\Batch Processing\"; // Path
to find files
// Find the files in the folder specified by path$ variable (default)
// The result file names are stored in the string variable fname$
// Separated by CRLF (default). Here wild card * is used, which means
// all files start with "T", and with the extension "csv"
findFiles ext:="T*.csv";
Batch processing using X-Functions can also be performed by calling Origin from an external
console; for more see Running Scripts From Console.
272
19 Function Reference
LabTalk-Supported Functions
LabTalk-Supported X-Functions
Below is a tabular listing of functions supported by the Set Values's F(x) menu, broken down by
category.
char(65)$ returns A.
Char(number)$
char(col(B))$ returns ASCII characters
273
LabTalk Scripting Guide
string in col(D).
compare(str1$,str2$,0) returns 1.
Compare(str1$, str2$ [,Case])
compare(col(F), col(G),1) returns "0"
exact(str1$,str2$) returns 0.
Exact(str1$, str2$)
exact(col(F), col(G)) returns "0" if not an
case).
274
Function Reference
lower case.
275
LabTalk Scripting Guide
'This','is','a','test','value'.
comma-separated values.
returns 1.
MatchBegin(str1$,str2$,1); returns 1.
276
Function Reference
str2$ = "From*@";
returns abc.
abcdef.
Replace(abcdefghijklmn,3,5,123456)$
replace(col(a),1,4,"Replacement
277
LabTalk Scripting Guide
spaces).
col(c).
Substitute(abcdefabcdef,12,bcd,0)$
returns a12efa12ef.
278
Function Reference
Text(Date(7/10/2014),D1)$ returns
str1$="This is my string";
col(c).
279
LabTalk Scripting Guide
ABCDE.
Upper(str$)$
upper(col(c))$ returns the string in col(c) in
uppercase letters.
(missing value);
abs(x)
abs(col(b)) returns absolute value of every
element in col(b).
280
Function Reference
distance(0,0,0,1) returns 1.
Distance(px1, py1, px2, py2)
distance(col(g),col(h),col(i),col(j))
distance3d(0,0,1,0,0,2) returns 1.
Distance3D(px1, py1, pz1, px2, py2,
pz2) distance3d(col(a),col(b),col(c),col(d),c
281
LabTalk Scripting Guide
value in col(a).
returns 11388.7402734106;
mod(16,7) returns 2.
mod(n, m)
mod(col(a),col(b)) returns the integer modulus
282
Function Reference
mod(5,-3) returns -1
by 3.
283
LabTalk Scripting Guide
by 3.
284
Function Reference
incgamma(a,x)
jn(x, n)
yn(x, n) where
Note: Angular units (radians, degrees, gradians) depend upon system.math.angularunits property
(also set in Tools: Options: Numeric Format).
285
LabTalk Scripting Guide
the X axis.
Returns the angle between two lines, one with endpoints (px1, py1) and (px2, py2),
the other with endpoints (px3, py3) and (px4, py4). If option unit = 0 (default),
returns radians; if unit = 1 returns degrees. Option direction specifies direction of
return value. If option direction = 0 (default), constrains the returned angular value
Angleint2(p to the first (+x,+y) and fourth (+x,-y) quadrants; if direction = 1, returns values
x1, py1, from 0–2pi radians or 0–360 degrees. examples:
px2, py2,
px3, py3, angleint2(0,0,1,0,0,1,0,0,1,1) returns 90.
px4, py4 [,
unit, angleint2(col(a),col(b),col(c),col(d),col(e),col(f),col(g),
direction])
col(h),1,1) returns the angle (degrees, 0 - 360) between two lines defined by
Returns the arcsecant of x. If |x| is < 1, returns missing value ("--"). Values are
asec(x)
returned in the first or second quadrant.
Returns the inverse hyperbolic secant of x. 0 < x ≤ 1. Other values of x return a
asech(x)
missing value ("--").
asin(x) Returns the arcsine of x. -1 ≤ x ≤ 1. Other values of x return a missing value ("--").
asinh(x) Returns the inverse hyperbolic sine of x (any real number).
atan(x) Returns the arctangent of x (any real number).
Takes coordinates x,y (doubles), returns the angle between the positive X axis and
the point (x,y). A variation of the atan(x) function. Returns value between -π and π.
atan2(y,x)
Angle is (+) for counter-clockwise angles (y > 0) and (-) for clockwise angles (y <
0).
286
Function Reference
Returns the inverse hyperbolic tangent of x. -1 < x < 1. Other values of x return a
atanh(x)
missing value ("--").
cos(x) Returns the cosine of x.
cosh(x) Returns the hyperbolic cosine of x.
cot(x) Returns the cotangent of x.
Returns the hyperbolic cotangent of x. Value x is any non-zero number. Note that
coth(x)
numbers of absolute value > 710 (approx.) return a missing value ("--").
csc(x) Returns the cosecant of x. If x = 0, returns missing value ("--").
Returns the hyperbolic cosecant of x. Value x is any non-zero number. Note: when
csch(x)
x > 710 (approx.), returns a missing value ("--").
Degrees(ang
Takes angle in radians and returns degrees.
le)
Radians(ang
Takes angle in degrees and returns radians.
le)
Returns the secant of x. Note: Do not confuse with the sec() function which returns
secant(x)
the seconds value of a date.
Returns the hyperbolic secant of x. Note that numbers of absolute value > 710
sech(x)
(approx.) return a missing value ("--").
sin(x) Returns the sine of x.
sinh(x) Returns the hyperbolic sine of x.
tan(x) Returns the tangent of x.
tanh(x) Returns the hyperbolic tangent of x.
287
LabTalk Scripting Guide
2446462.5506944.
string in col(a).
or
Takes doubles yy as year, mm as month, dd as date and returns
the Julian-date value.
Takes a Julian-date value and returns a date string. examples:
288
Function Reference
col(b).
value in col(b).
col(b).
289
LabTalk Scripting Guide
time2str(now()-date(col(a)),"HH:mm")$ returns a
Quarter(2454829.5745718) returns 4.
Quarter(d)
quarter(col(b)) returns the quarter of the Julian-date
value in col(b).
col(a).
290
Function Reference
formatted as DDD:HH.
weeknum(date(1/11/2009)) returns 3.
date value using the date() function and then returns a week
291
LabTalk Scripting Guide
date value using the date() function and then returns the
four-digit year.
col(C) = col(B)-mean(col(B));
fftc(cx) Takes a vector cx, returns the complex FFT result. Note that
(2015 SR1) the data type of output column needs to be set as complex (16)
292
Function Reference
in advance. examples:
signal in column B
Takes the sampling interval time and signal size n, returns the
frequencies for the FFT result. Option side defines the output
spectrum (1 = one-sided, 2 = two sided), shift defines whether
to shift for two-sided. ( 0 = no shift, 1 = shift).examples:
fftfreq(time, n[, side , shift]) fftfreq(0.001, 100) returns a dataset that starts
col(C) = col(B)-mean(col(B));
293
LabTalk Scripting Guide
vector
294
Function Reference
7.5.
returns 0.92064574677971.
values.
countif(vd, vcon) Takes a vector vd, returns the count of values satisfying
(2015 SR0) condition vcon.
Takes datasets vx and vy and respective means avex and avey,
returns the covariance. example:
returns 6.8926313172818.
295
LabTalk Scripting Guide
max(1,2,3,4,9) returns 9.
Interpolation of Quantiles.
member of vd1.
296
Function Reference
sumif(vd, vcon) Takes a vector vd, returns sum of values satisfying condition
(2015 SR0) vcon.
Takes a vector vd, returns the sum of elements. example:
297
LabTalk Scripting Guide
0.29399459768101.
Takes a vector vd, bin width = inc, vd min and vd max, and
histogram(vd, inc, min, max) generates data bins. Data points that fall on the upper edge of a
bin are placed into the next higher bin.
Takes a vector vd, returns the kurtosis. example:
298
Function Reference
column A.
row 10.
299
LabTalk Scripting Guide
col(2)[10]).
slope at each point (first and last two cells are missing
values).
300
Function Reference
example:
//data vector
//weight vector
col(3)=wmovavg(col(1),col(2));
betacdf(x,a,b)
binocdf(k,n,p)
301
LabTalk Scripting Guide
fcdf(f,ndf,fdf)
Computes the lower tail probability for gamma variate g with real
degrees of freedom, using shape parameter a and scale parameter b.
gamcdf(g,a,b)
where
Computes the lower tail probabilities in a given value, associated with
a hypergeometric distribution using the corresponding parameters.
hygecdf(k,m,n,l)
Computes the cdf with the lower tail of the non-central beta
distribution.
ncbetacdf(x,a,b,lambda) where
302
Function Reference
Computes the probability associated with the lower tail of the non-
central chi-square distribution.
ncchi2cdf(x,f,lambda)
= ,
Where
ncfcdf(f,df1,df2,lambda)
nctcdf(t,df,delta,maxiter)
with
303
LabTalk Scripting Guide
where ,
Computes the cumulative distribution function of Student's t-
distribution.
tcdf(t,df)
wblcdf(x,a,b)
with
Returns the probability density function of the binomial
distribution with parameters nt and p.
binopdf(x,nt,p)
(2015 SR0)
where and .
Cauchy probability density function (aka Lorentz distribution).
cauchypdf(x,a,b)
(8.6 SR0)
304
Function Reference
(8.6 SR0)
lappdf(x,mu,b)
(8.6 SR0)
305
LabTalk Scripting Guide
finv(p,df1,df2)
where ;
Computes the inverse of Gamma cumulative density function at p , with
parameters a and b.
gaminv(p,a,b)
where ;
Computes the deviate,x, associated with the given lower tail probability,p, of
logninv(p,mu,sig the Lognormal distribution with parameters mu and sigma.
ma)
(2015 SR0)
where
Computes the deviate, x, associated with the given lower tail probability, p,
of the standardized normal distribution.
norminv(p)
where
Computes the deviate, x, associated with the lower tail probability of the
srangeinv(p,v,ir)
distribution of the Studentized range statistic.
306
Function Reference
Computes the deviate associated with the lower tail probability of Student's t-
distribution with real degrees of freedom.
tinv(p,df)
,
Computes the inverse Weibull cumulative distribution function for the given
probability using the parameters a and b.
wblinv(p,a,b)
307
LabTalk Scripting Guide
0.33882089669989.
308
Function Reference
with mean of 5.
dataset
aa=findmasks(col(b));
Findmasks(vd)
col(d)=aa fills column D with
in column B.
index(170,col(1)); returns
309
LabTalk Scripting Guide
first occurs.
310
Function Reference
xindex(5,book1_g,1)
xvalue(20,book4_c) returns
Xvalue(n,vd) the x value associated with
C of Book4.
Errof(vd) %a=errof(book1_b)might
return book1_c.
311
LabTalk Scripting Guide
aa=hasx(book1_b) returns 1
a plot of column B.
ismasked(0,book1_b)
book1_b.
ismasked(8,book1_b)
masked, or 1 if it is masked.
%a = xof(book1_b);
312
Function Reference
the X values.
Takes two datasets vx and vy, a lag size k and returns the
correlation between the two datasets. Option n is the number of
points. Lag parameter k can be scalar or vector. When k is a vector,
function returns a vector; when a scalar, returns a scalar. example:
313
LabTalk Scripting Guide
19.2.12.2 Bessel
Name Brief Description
Bessel i0. Evaluates an approximation to the modified Bessel
bessel_i0(x)
function of the first kind, I0(x).
bessel_i0_scaled(x) Bessel i0 scaled. Evaluates an approximation to
Bessel i1. Evaluates an approximation to the modified Bessel
bessel_i1(x)
function of the first kind, .
bessel_i1_scaled(x) Bessel i1 scaled. Evaluates an approximation to
Bessel i nu. Evaluates an approximation to the modified Bessel
bessel_i_nu(x,n)
function of the first kind I /4 (x)
Bessel i nu scaled. Evaluates an approximation to the modified
bessel_i_nu_scaled(x,n)
Bessel function of the first kind
bessel_j0(x) Bessel j0. Evaluates the Bessel function of the first kind,
Bessel j1. Evaluates an approximation to the Bessel function of the
bessel_j1(x)
first kind
Bessel k0. Evaluates an approximation to the modified Bessel
bessel_k0(x)
function of the second kind,
bessel_k0_scaled(x) Bessel k0 scaled. Evaluates an approximation to
Bessel k1. Evaluates an approximation to the modified Bessel
Bessel_k1(x)
function of the second kind,
bessel_k1_scaled(x) Bessel k1 scaled. Evaluates an approximation to
Bessel k nu. Evaluates an approximation to the modified Bessel
bessel_k_nu(x,n)
function of the second kind
Bessel k nu scaled. Evaluates an approximation to the modified
bessel_k_nu_scaled(x,n)
Bessel function of the second kind
Bessel y0. Evaluates the Bessel function of the second kind, , x >
bessel_y0(x)
0. The approximation is based on Chebyshev expansions.
314
Function Reference
Bessel y1. Evaluates the Bessel function of the second kind, ,x>
bessel_y1(x)
0. The approximation is based on Chebyshev expansions.
19.2.12.3 Error
Name Brief Description
erf(x) The error function (or normal error integral).
Calculates an approximate value for the complement of the error
erfc(x)
function.
Computes the value of the inverse complementary error function for
erfcinv(dy)
specified y.
erfcx(x) The scaled complementary error function.
erfinv(dy) The inverse error function.
19.2.12.4 Gamma
Name Brief Description
gamma(x)
Gamma function. Evaluates
incomplete_gamma(a,x) Incomplete gamma function.
log_gamma(x) Log gamma function. Evaluates .x > 0.
Polygamma function. Evaluates an approximation to the kth derivative
real_polygamma(x,k)
of the psi function
19.2.12.5 Integral
Name Brief Description
NAG cosine integral function. Evaluates
cos_integral(x)
315
LabTalk Scripting Guide
sin_integral(x)
NAG sine integral function. Evaluates
19.2.12.6 Kelvin
Name Brief Description
kelvin_bei(x) Evaluates an approximation to the Kelvin function bei x.
kelvin_ber(x) Evaluates an approximation to the Kelvin function ber x.
kelvin_kei(x) Evaluates an approximation to the Kelvin function kei x.
kelvin_ker(x) Evaluates an approximation to the Kelvin function ker x.
19.2.12.7 Miscellaneous
Name Brief Description
NAG Jacobian theta function. Computes the value of one of the
Jacobian theta functions , , , or
jacobian_theta(k,x,q)
for a real argument x and non-negative q ≤ 1..
Calculates an approximate value for the real branches of Lambert's
lambertW(x,branch,offset)
W function.
316
Function Reference
description, a sample curve, a discussion of the parameters, and the LabTalk function syntax for each
multi-parameter function.
Beta(x,y0,xc,A,w1,w2,w3)
317
LabTalk Scripting Guide
318
Function Reference
function.
(y0 = offset, xc = center, A =area, wG = Gaussian FWHM, wL
= Lorentzian FWHM)
19.2.13.2 Implicit
Name Brief Description
Implicit circle equation with parameters circle center and radius.
Circle(x,y,xc,yc,r)
Implicit ellipse equation whose major and minor axes coincide with
XY axes.
Ellipse(x,y,xc,yc,a,b)
19.2.13.3 Exponential
Name Brief Description
Asymptotic Regression Model - 1st
Asymptotic1(x,a,b,c) parameterization.
319
LabTalk Scripting Guide
320
Function Reference
321
LabTalk Scripting Guide
ExpGrow3Dec2(x,y0,xc,Ag1,tg1,Ag2,tg2,A
g3,tg3,Ad1,td1,Ad2,td2)
(2015 SR0)
Langevin(x,y0,xc,C)
322
Function Reference
19.2.13.4 Growth/Sigmoidal
Name Brief Description
Biphasic Dose Response Function.
BiDoseResp(x,A1,A2,LOGx01,LOGx02,h1,h2
,p)
323
LabTalk Scripting Guide
Logistic5(x,Amin,Amax,x0,h,s)
324
Function Reference
SRichards1(x,a,xc,d,k)
19.2.13.5 Hyperbola
Name Brief Description
Double Rectangular Hyperbola Function.
Dhyperbl(x,P1,P2,P3,P4,P5)
325
LabTalk Scripting Guide
19.2.13.6 Logarithm
Name Brief Description
Double logarithmic reciprocal function.
Bradley(x,a,b)
One-parameter logarithm.
Logarithm(x,A)
Beta(x,y0,xc,A,w1,w2,w3)
Bigaussian(x,y0,xc,H,w1,w2)
CCE(x,y0,xc1,A,w,k2,xc2,B,k3,xc
3)
326
Function Reference
ECS(x,y0,xc,A,w,a3,a4)
GaussMod(x,y0,A,xc,w,t0)
GCAS(x,y0,xc,A,w,a3,a4)
327
LabTalk Scripting Guide
InvsPoly(x,y0,xc,w,A,A1,A2,A3)
Logistpk(x,y0,xc,w,A)
PearsonIV(x,y0,A,m,v,alpha,lam)
PearsonVII(x,y0,xc,A,w,m)
328
Function Reference
Voigt(x,y0,xc,A,wG,wL)
Weibull3(x,y0,xc,A,w1,w2)
19.2.13.8 Piecewise
Name Brief Description
Piecewise linear function with two segments.
PWL2(x,a1,k1,xi1,k2)
PWL3(x,a1,k1,xi1,k2,xi2,k3)
329
LabTalk Scripting Guide
19.2.13.9 Polynomial
Name Brief Description
Constant base line function.
Constant(x,y0)
Poly(x, a0, a1, a2, a3, a4, a5, a6, a7, a8, 9th order polynomial.
a9)
4th order Polynomial function.
Poly4(x,A0,A1,A2,A3,A4)
19.2.13.10 Power
Name Brief Description
Classical Freundlich Model, has been used in the study of allometry.
Allometric1(x,a,b)
330
Function Reference
19.2.13.11 Rational
Name Brief Description
Brunauer-Emmett-Teller (BET) adsorption equation.
BET(x,a,b)
331
LabTalk Scripting Guide
332
Function Reference
19.2.13.12 Waveform
Name Brief Description
Sawtooth wave, a periodic function consisting of extreme case
asymmetric triangle waves.
SawtoothWave(x,x0,y0,
A,T)
SquareWave(x,a,b,x0,T)
333
LabTalk Scripting Guide
Chebyshev2D(x,y,z0,A1,A2,B1,B2,C1)
Cosine(x,y,z0,A1,A2,B1,B2,C1)
Extreme2D(x,y,z0,B,C,D,E,F)
ExtremeCum(x,y,z0,B,C,D,E,F,G,H)
334
Function Reference
GaussCum(x,y,z0,B,C,D,E,F)
Gaussian2D(x,y,z0,A,xc,w1,yc,w2,theta)
LogNormal2D(x,y,z0,B,C,D,E,F,G,H)
335
LabTalk Scripting Guide
2D quadratic polynomial.
Poly2D(x,y,z0,a,b,c,d,f)
2D power function.
Power2D(x,y,z0,B,C,D,E,F)
Voigt2D(x,y,z0,A,xc,w1,yc,w2,mu)
Voigt2DMod(x,y,z0,A,xc,w1,yc,w2,mu)
(2016 SR0)
19.2.13.14 PFW
Name Brief Description
Asymmetric double Sigmoidal function.
Asym2Sig(x,y0,xc,A,w1,w2,w
3)
336
Function Reference
BWF(x,y0,xc,H,w,q)
ECS(x,y0,xc,A,w,a3,a4)
FraserSuzuki(x,y0,xc,A,sig)
Where
,
Area version of Gaussian Function.
(y0 = offset, xc = center, w = width, A = area)
Gauss(x, y0, xc, w, A)
337
LabTalk Scripting Guide
GaussMod(x,y0,A,xc,w,t0)
GCAS(x,y0,xc,A,w,a3,a4)
Lorentzian peak function with bell shape and much wider tails
Lorentz(x, y0, xc, w, A) than Gaussian function.
(y0 = offset, xc = center, w = FWHM, A = area)
338
Function Reference
PearsonVII(x,y0,xc,A,w,m)
Pulse(x,y0,x0,A,t1,P,t2)
339
LabTalk Scripting Guide
, ,
sine square function.
Sinesqr(x,xc,w,A,y0)
Weibull3(x,y0,xc,A,w1,w2)
19.2.13.15 Baseline
Name Brief Description
Constant base line function.
Constant(x,y0)
340
Function Reference
19.2.13.16 Chromatograph
Name Brief Description
Chesler-Cram Peak Function for use in chromatography.
CCE(x,y0,xc1,A,w,k2,xc2,B,k3,x
c3)
ECS(x,y0,xc,A,w,a3,a4)
341
LabTalk Scripting Guide
GaussMod(x,y0,A,xc,w,t0)
GCAS(x,y0,xc,A,w,a3,a4)
19.2.13.17 Electrophysiology
Name Brief Description
Transformed Boltzmann function for IV data.
BoltzIV(x,vhalf,dx,gmax,vrev)
342
Function Reference
Goldman(x,b,Nao,Nai,Ki,T)
19.2.13.18 Pharmacology
Name Brief Description
Biphasic Dose Response Function.
BiDoseResp(x,A1,A2,LOGx01,LOGx02,h1,
h2,p)
343
LabTalk Scripting Guide
19.2.13.19 Rheology
Name Brief Description
Bingham model to describe viscoplastic fluids exhibiting a yield
Bingham(x,y0,A)
response.
(2015 SR0)
Vogel-Fulcher-Tammann Equation.
VFT(x,A,B,x0)
(2015 SR0)
Mauro-Yue-Ellison-Gupta-Allan Equation.
MYEGA(x,y0,K,C)
(2015 SR0)
344
Function Reference
NoncompInhib(x,Vmax,Km,Ki,Ic)
(2015 SR0)
Note that this function is usually used in global fit,
Vmax, Km and Ki should be shared, and Ic should
be fixed for each dataset. The initial value of Ki can
be the mean of Ic.
Uncompetitive inhibition model for single
substrate and single inhibitor.
UncompInhib(x,Vmax,Km,Kia,Ic)
(2015 SR0)
Note that this function is usually used in global fit,
Vmax, Km and Kia should be shared, and Ic
should be fixed for each dataset. The initial value
of Kia can be the mean of Ic.
A general equation including competitive,
uncompetitive and noncompetitive inhibition as
special cases.
MixedModelInhib(x,Vmax,Km,Ki,Alpha,Ic)
(2015 SR0)
This fitting function is for global fitting. When using
it, Vmax, Km, Ki, and Alpha are shared, while Ic is
a fixed constant. The initial value of Ki can be the
mean of Ic.
Substrate inhibition model at high concentrations.
SubstrateInhib(x,Vmax,Km,Ki)
(2015 SR0)
345
LabTalk Scripting Guide
19.2.13.21 Spectroscopy
Name Brief Description
Amplitude version of Gaussian peak function.
GaussAmp(x,y0,xc,w,A) (y0 = offset, xc = center, w = width, A = amplitude)
Lorentzian peak function with bell shape and much wider tails
than Gaussian function.
Lorentz(x, y0, xc, w, A) (y0 = offset, xc = center, w = FWHM, A = area)
PearsonVII(x,y0,xc,A,w,m)
346
Function Reference
Voigt(x,y0,xc,A,wG,wL)
19.2.13.22 Statistics
Name Brief Description
Exponential growth function with rate constant parameter.
Exponential(x,y0,A,R0)
ExponentialCDF(x,y0,A,mu)
(2016 SR0)
347
LabTalk Scripting Guide
PearsonIV(x,y0,A,m,v,alpha,lam)
348
Function Reference
WeibullCDF(x,y0,A1,a,b)
(2016 SR0)
Lorentzian peak function with bell shape and much wider tails
Lorentz(x, y0, xc, w, A) than Gaussian function.
(y0 = offset, xc = center, w = FWHM, A = area)
349
LabTalk Scripting Guide
Voigt(x,y0,xc,A,wG,wL)
19.2.14 Miscellaneous
Name Brief Description
BitAND(n1, n2) Returns bitwise AND operation of two integers.
BitOR(n1, n2) Returns bitwise OR operation of two integers.
BitXOR(n1, n2) Returns bitwise XOR operation of two integers.
ISNA(d) Determines whether the number is a NANUM.
isText(str$) Determine whether a value is a text. Return 1 for text; return 0 for
(2015 SR0) numeric value or NANUM.
NA() Returns NANUM.
xf_get_last_error_code() Get the last error code value of XFunction engine.
xf_get_last_error_message()$ Get the last error string message of XFunction engine.
19.2.15 Engineering
Name Brief Description
Bin2Dec(str$) Convert a binary number to decimal.
Convert(d,str1$,str2$) Convert a number from one measurement system to another.
Convert a decimal number to binary. The input range is limited to -512 to
Dec2Bin(n)$
511.
Dec2Hex(n)$ Convert a decimal number to hexadecimal.
Hex2Dec(str$) Convert a string representation of a hexadecimal number to decimal.
19.2.16 Complex
Name Brief Description
Imabs(c) Get the modulus of a complex number.
350
Function Reference
Imaginary(c) This function is used to get the imaginary part of a complex number.
Imargument(c) Get the argument (theta) of a complex number.
Imatan(c)
Calculate the inverse tangent of a complex number.
(2016 SR0)
Imatanh(c)
Calculate the inverse hyperbolic tangent of a complex number.
(2016 SR0)
Imconjugate(c) Get the conjugate of a complex number.
Calculate the cosine value for a complex number.
Imcos(c)
where C is a complex, and .
Imdiv(c1,c2) Calculate the complex division.
Calculate the exponential value for a complex number.
Imexp(c)
where .
Calculate the natural logarithm of the complex number.
Imln(c)
where ImAbs computes the modulus of the complex,
Calculate the base 10 logarithm of a complex number.
Imlog10(c)
where ImLn computes the natural logarithm of the complex, and
.
Calculate the base 2 logarithm of a complex number.
Imlog2(c)
where ImLn computes the natural logarithm of the complex, and
.
ImPower(c,d) Calculate the given complex to the power of the specified value.
Perform the product (multiplication) operation of two complex
numbers.
Improduct(c1,c2)
Imsin(c)
where C is complex, and .
351
LabTalk Scripting Guide
the real part uses values from column A, imaginary part from
column B
This is not a complete list of X-Functions in Origin, but only those supported by
LabTalk! For a complete listing of all X-Functions, arranged by category and
alphabetical, see the X-Function Reference.
352
Function Reference
addsheet Set up data format and fitting function for Assays Template
cxt Shift the x values of the active curve with different mode
mc2ri Convert complex numbers in a matrix into their real parts and imaginary parts.
Convert a matrix layer with multiple matrix objects to a matrix page with
mo2s
multiple matrix layers.
Merge (move) multiple matrix sheets into one single matrix sheet with multiple
ms2o
matrixobjects.
353
LabTalk Scripting Guide
reduce_ex Average data points to reduce data size and make even spaced X
Subtract the active plot from a straight line formed with two points picked on the
subtract_line
graph page
vap2c Combine amplitude vector and phase vector to form a complex vector.
Convert a complex vector into a vector for the amplitudes and a vector for the
vc2ap
phases.
vc2ri Convert complex numbers in a vector into their real parts and imaginary parts.
vfind Find all vector elements whose values are equal to a specified value
Construct a complex vector from the real parts and imaginary parts of the
vri2c
complex numbers
19.3.2.1 Gridding
Convert the worksheet data directly into a matrix, whose coordinates can be
w2m
specified by first column/row and row labels in the worksheet.
354
Function Reference
19.3.2.2 Matrix
mdim Set the dimensions and values of XY coordinates for the active matrix
mexpand Expand for every cell in the active matrix according to the column and row factors
msetvalue Assign each cell in the active matrix from the user definited formula
19.3.2.3 Plotting
355
LabTalk Scripting Guide
Plot color fill surfaces or colormap surfaces for all matrix objects in the specified
plotms
matrix sheet.
19.3.2.4 Worksheet
filltext Fill the cell in the specified range with random letters
sparklines Add thumbnail size plots of each Y column above the data
updateSparklines Add thumbnail size plots of each Y column above the data
356
Function Reference
Set cell(s) color to fill color or set the selected character font color to
wcellcolor
Font color.
wks_update_link_table Update the contents in the worksheet to the linked table on graph
wproperties Get or set the worksheet property through a tree from script
wsplit_book Split specific workbooks into multiple workbooks with single sheet
357
LabTalk Scripting Guide
dbPreview Import to certain top rows for previewing the data from the query
19.3.4 Fitting
358
Function Reference
axis_scrollbar Add a scrollbar object to graph to allow easy zooming and panning
Add a pair of inverted triangles to the bottom X-Axis that allows easy
axis_scroller
rescaling
For a given X value, find all Y values from all curves and add them as a
gxy2w
row to a worksheet
laytoggle Toggle the left axis and bottom axis on and off.
359
LabTalk Scripting Guide
19.3.6 Image
19.3.6.1 Adjustments
imgHistcontrast Adjust the contrast of image, using histogram to calculate the median.
360
Function Reference
19.3.6.2 Analysis
19.3.6.4 Conversion
imgInfo Print out the given image's basic parameters in script window
361
LabTalk Scripting Guide
362
Function Reference
expNITDM Export workbook data as National Instruments TDM and TDMS files
impCDF Import CDF file. It supports the file version lower than 3.0
Import EarthProbe (EPA) file. Now only EPA file is supported for EarthProbe
impEP
data.
impHDF5 Import HDF5 file. It supports the file version lower than 1.8.2
impJNB Import SigmaPlot (JNB) file. It supports version lower than SigmaPlot 8.0.
Import ETAS INCA MDF (DAT, MDF) files. It supports INCA 5.4 (file version
impMDF
3.0).
363
LabTalk Scripting Guide
Import Minitab file (MTW) or project (MPJ). It supports the version prior to
impMNTB
Minitab 13.
impNetCDF Import netCDF file. It supports the file version lower than 3.1.
Import National Instruments TDM and TDMS files(TDMS does not support
impNITDM
data/time format)
Import pCLAMP file. It supports pClamp 9 (ABF 1.8 file format) and pClamp 10
imppClamp
(ABF 2.0 file format).
impSPE Import Princeton Instruments (SPE) file. It supports the version prior to 2.5.
insertImg2g Insert Images From Files:Insert graphic file(s) into Graph Window
19.3.8 Mathematics
Name Brief Description
integ2 Calculate the volume beneath the matrix surface from zero panel.
364
Function Reference
365
LabTalk Scripting Guide
corr2 2D correlation.
19.3.9.1 FFT
19.3.9.2 Wavelet
366
Function Reference
19.3.10 Spectroscopy
Name Brief Description
fitpeaks Pick multiple peaks from a curve to fit Guassian or Lorentzian peak functions
paMultiY Peak Analysis batch processing using Analysis Theme to generate summary report
19.3.11 Statistics
19.3.11.1 Descriptive Statistics
367
LabTalk Scripting Guide
368
Function Reference
19.3.12 Utility
themeEdit Edit the specific theme file using Theme Editing tool.
19.3.12.1 File
cmpfile Compare two binary files and print out comparison results
Create a .txt file that contains notes or records of the user's work through a
filelog
string
19.3.12.2 System
369
LabTalk Scripting Guide
Used to create a debug log file. Turn on only if you have a problem to
debug_log
report to OriginLab.
dir list script (ogs) and x-functions (oxf) in current working directory.
Open a dialog with check boxes and return each check box's selected
dlgChkList
status when the dialog is closed.
group_server Set up the Group Folder location for both group leader and members
pe_load Load an Origin project into an existing folder in the current project
pe_save Save a folder from the current project to an Origin project file
370
Function Reference
371
20 Appendix
List of LabTalk related help materials:
Reference Location
X-
Reference of individual X-Function.
Function
Code
How to use Code Builder.
Builder
Tutorials A simple introductory tutorial for how to run LabTalk commands and X-
Functions.
Web site:
http://www.originlab.com/index.aspx?go=Products/Origin/ImportingData&pid=1163
Video
Learn how to run LabTalk Script after importing data.
373
Index
$ Before Formula Scripts .................................. 125
$( ) Substitution ..........................................73, 80 block................................................................. 32
$(num) ............................................................ 157 block of cells .................................................... 61
braces .............................................................. 32
%
break ................................................................ 45
% variables....................................................... 90
C
%( ) Substitution ............................................... 73
%( ) substitution notation ................................. 68 Calculation Using Interpolation ........................ 41
%(string$) ....................................................... 157 calculations involving columns ........................ 76
%A - %Z ........................................................... 73 call a fitting function ......................................... 53
%n, Argument .................................................. 84 Calling Origin C Function from LabTalk ......... 110
Calling X-Functions and Origin C Functions97, 240
@
cd ................................................................... 123
@ option ........................................................... 78 Code Builder .......................................... 117, 143
@ Substitution .................................................. 77 Code Builder, script access ........................... 144
@ variable ........................................................ 78 colon-equal ...................................................... 95
A column dataset name ...................................... 74
access worksheet cell ...................................... 74 Column Format .............................................. 183
Active Column ................................................ 168 Column Header .............................................. 241
active dataset ................................................... 90 Column Label ......................................... 181, 241
active graph layer ........................................... 210 Column Label Row ........................................ 241
Active Matrixbook .............................168, 196–95 Column Width ................................................ 183
Active Window................................................ 168 Columns, Loop over ....................................... 249
active window title ............................................ 90 COM Server ................................................... 132
active worksheet .............................................. 60 command history ........................................... 116
Add Layer ....................................................... 213 command statement ........................................ 29
Addition ............................................................ 35 Command Window .................................. 70, 115
after fit script................................................... 132 command-line ................................................ 133
Analysis Template ..................................321, 324 comment .......................................................... 33
and operator ..................................................... 44 Comments ..................................................... 240
And operator .................................................... 35 Composite Range ............................................ 72
Append project ............................................... 238 conditional operator ......................................... 39
area ................................................................ 259 console........................................................... 133
Argument Order ............................................. 98 Constant .......................................................... 13
Argument, Command Statment ....................... 29 continue ........................................................... 45
Argument, Macro.............................................. 47 control characters ............................................ 74
Argument, Subsitution ...................................... 84 convert a numeric date value ........................ 191
Argument, X-Function .................................... 101 Convert Number to String .............................. 157
Arithmetic ....................................................... 187 Convert String to Number .............................. 156
arithmetic operator ........................................... 35 Converting Image to Data .............................. 288
arithmetic statement ......................................... 30 Copy Column ................................................. 188
ASCII ......................................................223, 230 Copy Matrix .................................................... 200
assignment operator .................................... 2, 37 Copy Range ................................................... 170
assignment statement ...................................... 27 correlation coefficient ..................................... 267
Assignment, X-Function Argument .................. 95 Cox Proportional hazards model ................... 272
Average Curves ............................................. 258 Create Baseline ............................................. 283
Axis Property .................................................. 211 Create Graph ................................................. 205
Axis Title Substitution ....................................... 80 Create Script File ........................................... 117
current baseline dataset .................................. 90
B current project name ........................................ 90
baseline .......................................................... 283 current working directory ............................... 122
batch processing ............................................ 323 current working folder .................................... 122
Batch Processing ........................................... 323 Current Working Folder ................................. 122
375
LabTalk Scripting Guide
376
Index
377
LabTalk Scripting Guide
program path .................................................... 90 Run Script from Graphic Object ..................... 127
project level loose dataset ............................... 14 Run Script from Import Wizard ...................... 131
Project Management ...................................... 237 Run Script from Nonlinear Fitter .................... 132
Project variables............................................... 22 Run Script from Script Panel ......................... 127
ProjectEvents.ogs .......................................... 129 Run Script from Set Values Dialog ................ 125
PyOrigin ......................................................... 316 Run Script On a Timer ................................... 133
PyQt4 ............................................................. 318 S
Python ............................................................ 313
Sampling Interval ........................................... 240
Python Binding ............................................... 318
Save Window ................................................. 238
Python Command .......................................... 313
Scalar Calculations .......................................... 40
Python Expression ......................................... 315
Scientific Notation .......................................... 159
Python Extension ........................................... 318
scipy ............................................................... 318
Python File ..................................................... 315
scope of a function ........................................... 53
Python Module ............................................... 316
Scope of String Register .................................. 89
Q scope of variables ............................................ 21
Quick Output ...................................................... 2 scope, forcing change of.................................. 24
R scope, local ...................................................... 23
scope, project .................................................. 22
range ................................................................ 16
scope, session ................................................. 22
Range Data Manipulation ................................ 67
Screen Reader ............................................... 296
Range Notation ................................................ 57
script .............................................. 117, 127, 133
Range to UID ................................................... 71
Script .............................................................. 133
range variable .................................................. 87
Script After Fitting .......................................... 132
Range, Block of Cells ....................................... 61
Script Panel ................................................... 127
Range, Column ................................................ 59
Script Section ................................................. 117
Range, Column Subrange ............................... 61
Script Window .................... 1, 3, 5, 115, 116, 117
Range, Get plot X............................................. 63
Script, Before Formula ................................... 125
Range, Get plot Y............................................. 63
script, debugging ........................................... 141
Range, Get plot Z ............................................. 63
script, execution ............................................. 113
Range, Graph Data .......................................... 63
Script, Fitting .................................................. 276
Range, Matrix Data .......................................... 62
Script, for specified window ........................... 114
Range, Origin Object ....................................... 58
script, from a custom menu ........................... 138
Range, Page and Sheet ................................... 61
script, from a script panel............................... 127
Range, Worksheet Data ................................... 59
script, from a toolbar button ........................... 138
Range, X-Function Argument .......................... 69
script, from external console .......................... 133
recalculate ...................................................... 106
script, import wizard/filter ............................... 131
recognition order .............................................. 33
script, in set values dialog.............................. 125
Reduce Worksheet Data ................................ 170
script, in worksheet script dialog .................... 126
refresh window ............................................... 239
script, interactive execution ................... 141, 150
Regional Data Selector .................................. 298
Script, Project events ..................................... 129
Regional Mask Tool ....................................... 298
script, run ....................................................... 113
Regression ..................................................... 274
section.............................................................. 45
Rename matrix sheet ..................................... 196
Select Range on Graph ................................... 64
Rename worksheet ........................................ 168
semicolon ................................................... 26, 31
repeat ............................................................... 42
separate statements ........................................ 31
ReportData ..................................................... 103
Session variables ............................................. 22
resolution ........................................................ 231
Set.................................................................. 211
RHS .................................................................. 27
Set Column Value .......................................... 322
Rotate image .................................................. 285
Set Column Values ........................................ 188
Row-by-Row Calculations ................................ 40
Set Decimal Places ........................................ 158
Rows, Delete .................................................. 181
set matrix value .............................................. 200
Rows, Looping over ....................................... 249
Set Path ......................................................... 122
Run Script ...................................................... 113
Set Significant Digits ...................................... 158
Run Script from Command Window............... 115
Set Values Dialog .......................................... 125
Run Script from External Application ............. 132
Signal Processing .......................................... 278
Run Script from File ....................................... 117
378
Index
379