Diogo Cosin
Diogo Cosin

Reputation: 107

Most efficient way to exchange data between MATLAB and C++?

I'm developing an application where there are two programs, running at the same time: one in C++ and another in MATLAB.

The C++ program generates periodically three numerical values as outputs. The MATLAB program needs an access to the three outputs periodically, but in a different period of time.

Currently, I've solved this using a .txt file. The C++ writes this file when the routine is done, and the MATLAB reads from it whence it needs.

However, using textscan command, MATLAB takes around 1.5 ms to read the .txt using a Pentium I5-4250U. So, I was wondering if there is a faster way to solve this issue.

Upvotes: 2

Views: 1378

Answers (1)

user3666197
user3666197

Reputation: 1

A: Yes, use a messaging layer

If no other services are needed, the C++ side will act as an information provider ( ZMQ.PUB publisher ) and MATLAB side will act as an information subscriber ( ZMQ.SUB ).

This way the low-level details related to the messaging are solved by the distributed-processing messaging layer and your solution will benefit from both speed, ready-made tools and can go distributed onto a private grid-computing / cloud-computing architectures, using the same instrumentation, gaining additional performance etc.

ZeroMQ has bindings for both C++ and MATLAB, so that is a place to start and taste the process-to-process messaging-layer approach.

% MATLAB script to setup zeromq-matlab
clear all;
if ~ispc
    s1 = zmq( 'subscribe', 'ipc', 'MATLAB' );   %% using IPC transport on <localhost>
else
    disp('0MQ IPC not supported on windows. Setup TCP transport class instead')
    disp('Setting up TCP')
    s1 = zmq( 'subscribe', 'tcp', 'localhost', 5555 );
end

recv_data1 = [];                                %% setup RECV buffer

The MATLAB bindings can be found here.

Having a few floats to send, the latencies will be somewhere under hundreds if not tens of [usec], as your notice mentioned asynchronous mode of data-dispatch, so the localhost will just spend some clocks on data retrieval from localhost ZMQ.SUB-queue.

More complex application-to-application signalling is possible, just get inspired by the ZeroMQ Guide

Upvotes: 4

Related Questions