In this article, I will show you how to move data between Matlab and Armadillo, specifically how to move matrices between the two. If you need an introduction in how to install Armadillo on your system, check my previous article.
Easiest approach is to transfer data between Matlab and Armadillo using text files. For example, the next Matlab code will generate some data and save it in a text file that can be loaded from Armadillo:
Reading the matrix from matlab_data.txt in Armadillo can be done with:
The above procedure works well if you need to transfer one or two matrices from Matlab to Armadillo, but it doesn’t scale. Imagine that you need to move many small matrices of various dimensions. Using a separate text file for every one of them is not only tedious and error prone, it is also a relatively slow process.
The .load() function from Armadillo also works with C++ streams, e.g.:
This last approach can be generalized for the case when you need to transfer more than one matrix from Matlab. The idea is to use some kind of delimiters between two records, read the content of the first record (matrix) in a C++ stringstream after which you can use the .load() function from Armadillo to get the data as a matrix in memory.
Here is a simple Matlab function that will let you save a matrix in a text file using start and end text delimiters:
An example of using the above function to save a few matrices in a text file:
This is the content of matlab_data_v2.txt on my machine (obviously this will be different for every run of the Matlab code):
The C++ code can simply read the data file line by line and accumulate the data between the delimiters in a strinstream, e.g.:
A more general approach is to use binary files to transfer data between Matlab and Armadillo, this is left as an exercise for the reader. Hint: read about Matlab’s fread, fwrite functions and their C++ counterparts.
If you are interested to learn more about the new C++11/C++14 syntax, I would recommend reading The C++ Programming Language by Bjarne Stroustrup.