# MATLAB Programming

The MathWorks' numerical computing environment MATLAB® has powerful tools for data analysis and visualization that can be used to create graphical user interfaces or automatically generate reports of experimental results in various formats. LabOne’s MATLAB API, also known as ziDAQ, "Zurich Instruments Data Acquisition", enables the user to stream data from their instrument directly into MATLAB allowing them to take full advantage of this powerful environment.

This chapter aims to help you get started using Zurich Instruments LabOne’s MATLAB API, ziDAQ, to control your instrument.

 For a full reference of the MATLAB API visit the LabOne API documentation.
 This section and the provided examples are not intended to be a MATLAB tutorial. See either MathWorks' online Documentation Center or one of the many online resources, for example, the MATLAB Programming Wikibook for help to get started programming with MATLAB.

## Installing the LabOne MATLAB API

### Requirements

One of the following platforms and MATLAB versions (with valid license) is required to use the LabOne MATLAB API:

1. 32 or 64-bit Windows with MATLAB R2009b or newer.

2. 64-bit Linux with MATLAB R2016b or newer.

3. 64-bit macOS and MATLAB R2013b or newer.

The LabOne MATLAB API ziDAQ is included in a standard LabOne installation and is also available as a separate package (see below, Separate MATLAB Package). No installation as such is required, only a few configuration steps must be performed to use ziDAQ in MATLAB. Both the main LabOne installer and the separate LabOne MATLAB API package are available from Zurich Instruments' download page.

 Separate MATLAB Package The separate MATLAB API package should be used if you would like to: Use the MATLAB API to work with an instrument remotely (i.e., on a separate PC from where the Data Server is running) and you do not require a full LabOne installation. This is the case, for example, with MF Instruments. Use the MATLAB API on a PC where you do not have administrator rights.

### Windows, Linux or Mac

No additional installation steps are required to use ziDAQ on either Windows, Linux or Mac; it’s only necessary to add the folder containing LabOne’s MATLAB Driver to MATLAB’s search path. This is done as following:

1. Start MATLAB and either set the "Current Folder" (current working directory) to the MATLAB API folder in your LabOne installation or the extracted zip archive of the separate MATLAB API package (see above, Separate MATLAB Package) as appropriate.

If using a LabOne installation on Windows this is typically:

C:\Program Files\Zurich Instruments\LabOne\API\MATLAB\

and on Linux this is the location where you unpacked the LabOne .tar.gz file:

[PATH]/LabOne64/API/MATLAB/

2. In the MATLAB Command Window, run the MATLAB script ziAddPath located in the MATLAB directory:

>> ziAddPath;

On Windows (similar for Linux and Mac) you should see the following output in MATLAB’s Command Window:

Added ziDAQ's Driver, Utilities and Examples directories to MATLAB's path
for this session.

To make this configuration persistent across MATLAB sessions either:

1. Run the 'pathtool' command in the MATLAB Command Window and add the
following paths WITH SUBFOLDERS to the MATLAB search path:

C:\Program Files\Zurich Instruments\LabOne\API\MATLAB\

or

run('C:\Program Files\Zurich Instruments\LabOne\API\MATLAB\ziAddPath');

This is sufficient configuration if you would only like to use ziDAQ in the current MATLAB session.

3. To make this configuration persistent between MATLAB sessions do either one of the next two steps (as also indicated by the output of ziAddPath):

1. Run the pathtool and click "Add with Subfolders". Browse to the "MATLAB" directory that was located above in Step 1 and click "OK".

2. Edit your startup.m to contain the line indicated in the output from Step 2 above. For more help on MATLAB’s startup.m file, type the following in MATLAB’s Command Window:

>> docsearch('startup.m')

4. Verify your MATLAB configuration as described in Verifying Successful MATLAB Configuration .

### Verifying Successful MATLAB Configuration

In order to verify that MATLAB is correctly configured to use ziDAQ please perform the following steps:

1. Ensure that the correct Data Server is running for your HDAWG, HF2 or UHF Instrument (the Data Server on MF Instruments starts when the device is powered on). The quickest way to check is to start the User Interface for your device, see LabOne Software Architecture for more details.

2. Proceed either of the following two ways:

1. The easiest way to verify correct configuration is run one of the MATLAB API’s examples (see <<pm.matlab.github_repository). In the MATLAB command Window run, for example, example_poll with your device ID as the input argument:

>> example_poll('dev123'); % Replace with your device ID.

If this fails, please try issuing the connect command, as described in the next method.

2. If a device is not currently available, correct MATLAB API configuration can be checked by initializing an API session to the Data Server without device communication.

An API session with the Data Server is created using ziDAQ’s connect (the port specifies which Data Server to connect to on the localhost) cf. Specifying the Data Server Hostname and Port ). In the MATLAB command window type one of the following:

* >> ziDAQ('connect', 'localhost', 8005) % 8005 for HF2 Series
* >> ziDAQ('connect', 'localhost', 8004, 6) % 8004 for HDAWG, UHFLI
* >> ziDAQ('connect', mf-hostname, 8004, 6) % 8004 for MFLI (see below)

Note, using 'localhost' above assumes that the Data Server is running on the same computer from which you are using MATLAB. See Specifying the Data Server Hostname and Port for information about ports and host names when connecting to the Data Server. For MFLI instruments the hostname/IP address of the MFLI instrument must be provided (the value of mf-hostname), see Specifying the Data Server Hostname and Port and the Getting Started chapter of the MFLI User Manual for more information.

3. If no error is reported then MATLAB is correctly configured to use ziDAQ - congratulations! Otherwise, please try the steps listed in Troubleshooting the LabOne MATLAB API .

## Getting Started with the LabOne MATLAB API

This section introduces the user to the LabOne MATLAB API.

### Contents of the LabOne MATLAB API

Alongside the driver for interfacing with your Zurich Instruments device, the LabOne MATLAB API includes many files for documentation, utility functions and examples. See the Contents.m file located in a LabOne MATLAB API directory (see Step 1 in Windows, Linux or Mac for its typical location) for a description of the API’s sub-folders and files. Run the command:

>> doc('Contents')

in the MATLAB Command Window in the LabOne MATLAB API directory or take a look at the LabOne API documentation for a detailed overview.

 MATLAB Driver Naming On Windows the MEX-file (the ziDAQ MATLAB Driver/DLL) is called either ziDAQ.mexw64 or ziDAQ.mexw32 for 64-bit and 32-bit platforms respectively, on Linux it’s called ziDAQ.mexa64 and on Mac it’s called ziDAQ.mexmaci64. When more than one MEX-file is present, MATLAB automatically selects the correct MEX-file for the current platform.

### Using the Built-in Documentation

To access ziDAQ’s documentation within MATLAB, type either of the following in the MATLAB Command Window:

>> help ziDAQ

>> doc ziDAQ

This documentation is located in the file MATLAB/Driver/ziDAQ.m. See the LabOne API documentation for a detailed overview.

### Running the Examples

Prerequisites for running the MATLAB examples:

1. MATLAB is configured for ziDAQ as described above in Installing the LabOne MATLAB API .

2. The Data Server program is running and the instrument is discoverable, this is the case if the instrument can be seen in the User Interface.

3. Signal Output 1 of the instrument is connected to Signal Input 1 via a BNC cable; many of the MATLAB examples measure on this hardware channel.

See Contents of the LabOne MATLAB API for a list of available examples bundled with the LabOne MATLAB API. All the examples follow the same structure and take one input argument: the device ID of the instrument they are to be ran with. For example:

>> example_sweeper('dev123');

The example should produce some output in the MATLAB Command Window, such as:

ziDAQ version Jul 7 2015 accessing server localhost 8005.
Will run the example on dev123, an HF2LI with options MFK|PLL|MOD|RTK|PID.
Sweep progress 9%
Sweep progress 19%
Sweep progress 30%
Sweep progress 42%
Sweep progress 52%
Sweep progress 58%
Sweep progress 68%
Sweep progress 79%
Sweep progress 91%
Sweep progress 100%
ziDAQ: AtExit called

Most examples will also plot some data in a MATLAB figure, see Figure 1 for an example. If you encounter an error message please ensure that the Running the Examples are fulfilled and see Troubleshooting the LabOne MATLAB API for help troubleshooting the error.

Figure 1. The plot produced by the LabOne MATLAB API example example_sweeper.m; the plots show the instruments demodulator output when performing a frequency sweep over a simple feedback cable.
 The examples serve as a starting point for your own measurement needs. However, before editing the m-files, be sure to copy them to your own user space (they could be overwritten upon updating your LabOne installation) and give them a unique name to avoid name conflicts in MATLAB.

### Using ziCore Modules in the LabOne MATLAB API

In the LabOne MATLAB API ziCore Modules are configured and controlled via MATLAB "handles". For example, in order to use the Sweeper Module a handle is created via:

>> h = ziDAQ('sweep');

and the Module’s parameters are configured using the set command and specifying the Module’s handle with a path, value pair, for example:

>> ziDAQ('set', h, 'start', 1.2e5);

The parameters can be read-back using the get command, which supports wildcards, for example:

>> sweep_params = ziDAQ('get', h, '*');

The variable sweep_params now contains a struct of all the Sweeper’s parameters. The other main Module commands are used similarly, e.g., ziDAQ('execute', h) to start the sweeper. See ziCore Modules for more help with Modules and a description of their parameters.

 The Data Acquisition Module uses dot notation for subscribing to signals. In the data structure returned by the MATLAB API, the dots are replaced by underscores in order not to conflict with the dot notation used for member selection in MATLAB, e.g. /devNNN/demods/0/sample.r is accessed using devNNN.demods(1).sample_r.

### Enabling Logging in the LabOne MATLAB API

Logging from the API is not enabled by default upon initializing a server session with ziDAQ, it must be enabled (after using connect) with the setDebugLevel command. For example,

>> ziDAQ('setDebugLevel', 0);

sets the API’s logging level to 0, which provides the most verbose logging output. The other log levels are defined as follows:

trace:0, debug:1, info:2, status:3, warning:4, error:5, fatal:6.

It is also possible for the user to write their own messages directly to ziDAQ’s log using the writeDebugLog command. For example to write a log message of info severity level:

>> ziDAQ('writeDebugLog', 1, 'Hello log!');

On Windows the logs are located in the directory C:\Users\[USER]\AppData\Local\Temp\Zurich Instruments\LabOne Note that AppData is a hidden directory. The easiest way to find it is to open a File Explorer window and type the text %AppData%\.. in the address bar, and navigate from there. The directory contains folders containing log files from various LabOne components, in particular, the ziDAQLog folder contains logs from the LabOne MATLAB API. On Linux, the logs can be found at "/tmp/ziDAQLog_USERNAME", where "USERNAME" is the same as the output of the "whoami" command.

## LabOne MATLAB API Tips and Tricks

In this section some tips and tricks for working with the LabOne MATLAB API are provided.

 The structure of ziDAQ commands. All LabOne MATLAB API commands are based on a call to the MATLAB function ziDAQ(). The first argument to ziDAQ() specifies the API command to be executed and is an obligatory argument. For example, a session is instantiated between the API and the Data Server with the MATLAB command ziDAQ('connect'). Depending on the type of command specified, optional arguments may be required. For example, to obtain an integer node value, the node path must be specified as a second argument to the 'getInt' command: s = ziDAQ('getInt','/dev123/sigouts/0/on'); where the output argument contains the current value of the specified node. To set an integer node value, both the node path and the value to be set must be specified as the second and third arguments: ziDAQ('setInt','/dev123/sigouts/0/on', 1);. See the LabOne API documentation for a detailed overview.
 Data Structures returned by ziDAQ. The output arguments that ziDAQ returns are designed to use the native data structures that MATLAB users are familiar with and that reflect the data’s location in the instruments node hierarchy. For example, when the poll command returns data from the instruments fourth demodulator (located in the node hierarchy as /dev123/demods/3/sample), the output argument contains a nested struct in which the data can be accessed by data = ziDAQ('poll', poll_length, poll_timeout); x = data.dev123.demods(4).sample.x; y = data.dev123.demods(4).sample.y;
 The instrument’s node tree uses zero-based indexing; MATLAB uses one-based indexing. See the tip Data Structures returned by ziDAQ.: The fourth demodulator sample located at /dev123/demods/3/sample, is indexed in the data structure returned by poll as data.dev123.demods(4).sample.
 Explicitly convert uint64 data types to double. MATLAB’s native data type is double-precision floating point and doesn’t support performing calculations with with other data types such as 64-bit unsigned integers, for example: >> a = uint64(2); b = uint64(1); a - b ? Undefined function or method 'minus' for input arguments of type 'uint64'. Due to this limitation, be sure to convert demodulator timestamps to double before performing calculations. For example, in the following, both clockbase and timestamp (both 64-bit unsigned integers) need to be converted to double before converting the timestamps from the instrument’s native "ticks" to seconds via the instrument’s clockbase: data = ziDAQ('poll', 1.0, 500); % poll data sample = data.(device).demods(0).sample; % get the sample from the zeroth demod % convert timestamps from ticks to seconds via the device's clockbase % (the ADC's sampling rate), specify reference start time via t0. clockbase = double(ziDAQ('getInt',['/' device '/clockbase'])); t = (double(sample.timestamp) - double(sample.timestamp(1)))/clockbase;
 Use the utility function ziCheckPathInData. Checking that a sub-structure in the nested data structure returned by poll actually exists can be cumbersome and can require multiple nested if statements; this can be avoided by using the utility function ziCheckPathInData. For example, the code: data = ziDAQ('poll', poll_length, poll_timeout ); if isfield(data,device) if isfield(data.(device),'demods') if length(data.(device).demods) >= channel if ~isempty(data.(device).demods(channel).sample) % do something with the demodulator sample... can be replaced by: data = ziDAQ('poll', poll_length, poll_timeout ); if ziCheckPathInData( data, ['/' device '/demods/' demod_c '/sample']); % do something with the demodulator sample...

## Troubleshooting the LabOne MATLAB API

This section intends to solve possible error messages than can occur when using ziDAQ in MATLAB.

 Error message: "Undefined function or method 'ziDAQ' for input arguments of type '*'" MATLAB can not find the LabOne MATLAB API library. Check whether the MATLAB/Driver subfolder of your LabOne installation is in the MATLAB Search Path by using the command: >> path and repeating the steps to configure MATLAB’s search path in Windows, Linux or Mac .
 Error message: "Undefined function or method 'example_sweeper'" MATLAB can not find the example. Check whether the MATLAB/Examples/Common subfolder (respectively MATLAB/Examples/HDAWG, MATLAB/Examples/HF2 or MATLAB/Examples/UHF) of your LabOne installation are in the MATLAB Search Path by using the command: >> path and repeating the steps to configure MATLAB’s search path in Windows, Linux or Mac .
 Error message: "Error using: ziDAQ ZIAPIException with status code: 32870. Connection invalid." The MATLAB API can not connect to the Data Server. Please check that the correct port was used; that the correct server is running for your device and that the device is connected to the server, see Specifying the Data Server Hostname and Port.
 Error Message: "Error using: ziAutoConnect at 63 ziAutoConnect() failed to find a running server or failed to find a connected a device…​" The utility function ziAutoConnect() located in MATLAB/Utils/ tries to determine which Data Server is running and whether any devices are connected to that Data Server. It is only supported by UHFLI and HF2 Series instruments, MFLI instruments are not supported. Some suggestions to verify the problem: Please verify in the User Interface, whether a device is connected to the Data Server running on your computer. If the Data Server is running on a different computer, connect manually to the Data Server via ziDAQ’s connect function: >> ziDAQ('connect', hostname, port, api_level); where hostname should be replaced by the IP of the computer where the Data Server is running, port is specified as in Specifying the Data Server Hostname and Port. and api_level is specified as described in LabOne API Levels.
 Error Message: "Error using: ziDAQ ZIAPIException on path /dev123/sigins/0/imp50 with status code: 16387. Value or Node not found" The API is connected to the Data Server, but the command failed to find the specified node. Please: Check whether your instrument is connected to the Data Server in the User Interface; if it is not connected the instruments device node tree, e.g., /dev123/, will not be constructed by the Data Server. Check whether the node path is spelled correctly. Explore the node tree to verify the node actually exists with the listNodes command: >> ziDAQ('listNodes', '/dev123/sigins/0', 3)
 Error Message: "using: ziDAQ Server not connected. Use 'ziDAQ('connect', …​) first." A ziDAQ command was issued before initializing a connection to the Data Server. First use the connect command: >> ziDAQ('connect', hostname, port, api_level); where hostname should be replaced by the IP address of the computer where the Data Server is running, port is specified as in Specifying the Data Server Hostname and Port and api_level is specified as described in LabOne API Levels. If the Data Server is running on the same computer, use 'localhost' as the hostname.
 Error Message: "Attempt to execute SCRIPT ziDAQ as a function: ziDAQ.m" There could be a problem with your LabOne MATLAB API installation. The call to ziDAQ() is trying to call the help file ziDAQ.m as a function instead of calling the ziDAQ() function defined in the MEX-file. In this case you need to ensure that the ziDAQ MEX-file is in your search path as described in Installing the LabOne MATLAB API and navigate away from the Driver directory. Secondly, ensure that the LabOne MATLAB MEX-file is in the Driver folder as described in Contents of the LabOne MATLAB API .