MSTTm
MSTTm

Reputation: 303

Quick and Efficient Method to Pass Variables from C++ to Matlab

I've developed a C++ program which calculates a set of coordinates (x, y) within a loop. Every iteration I want to send the coordinate to Matlab for further processing, at a speed of about 25 times per second. I have a Matlab function that then takes this coordinate and uses it in real time; however, I haven't found an effective way of sending variables quickly from C++ to Matlab.

I've tried using the Matlab engine here: Passing Variable from C++ to Matlab (Workspace), except I want this variable to be used in the existing Matlab session and not simply run Matlab commands through C++.

I've also tried writing the C++ coordinate to a binary file and then reading this file in Matlab - this method is very fast but I'm having problems with the timing between both languages. Setting the Matlab code to an infinite loop reading the binary file, whilst running the C++ program writing the coordinate to the file, means that Matlab reads in a very strange order (ie. Matlab reads 15, 200, 70, 12 when I write the i values to file). I suspect this is due to poor timing between each program trying to open and either read or write the file.

C++:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <math.h>
#include <fstream>
#include <stdio.h>
#include <Windows.h>

using namespace cv;
using namespace std;

int main()
{

    int a = 0

    for (int i = 0; i < 100000; ++i)
    {
        a = i;
        std::ofstream ofile("foobar.bin", std::ios::binary);
        ofile.write((char*) &a, sizeof(int));
        ofile.close();
    }

    return 0;
}

Matlab:

A = fopen('foobar.bin');
fread(A)
fclose(A);

Is there a way to quickly and accurately send data between C++ and Matlab by writing to binary OR some other method which I can implement?

Thank you very much!

Upvotes: 1

Views: 924

Answers (1)

MechanikalK
MechanikalK

Reputation: 11

I cannot provide code samples because it has been a few years since I did this, but I know that you can use a create a COM object and interface it with matlab. Here is the link describing how to interface a COM object with matlab. http://www.mathworks.com/help/matlab/using-com-objects-in-matlab.html

Upvotes: 1

Related Questions