xue3do
xue3do

Reputation: 21

how to load matlab matrix with armadillo?

I know matlab matrix can be loaded into C++ program in some ways, while none of these ways seem to be efficient or convenient. I have seen others modified the header of the '.mat' file, then it can be directly loaded into C++ program with armadillo.

Anyone has ideas how to modify the header file?

It's not just save the matlab '.mat' file into ascii format. The loading time and storage space is larger than binary format. To store a 2GB binary mat file, I need at least 20GB to store it in ASCII format. Loading 100MB binary mat file takes less than 1 second, load same size ASCII text data takes much longer.

I don't think save the matlab mat file into ASCII format and load it into armadillo is a good solution.

Upvotes: 1

Views: 6484

Answers (2)

Darkdragon84
Darkdragon84

Reputation: 911

You can export your data in matlab in low level binary format and then load it in armadillo with the arma::raw_binary option.

e.g. in MATLAB:

m=10;
A = randn(m,m);
name = 'test.bin'

[F,err] = fopen(name,'w');
if F<0,error(err);end

fwrite(F,A,'double');
fclose(F);

load with armadillo:

arma::mat A;
std::string name = "test.bin";

A.load(name,arma::raw_binary);
A.print("A");

The only thing is that you lose the matrix dimensions of the original matrix, as armadillo loads it in a vectorized form, so you have to reshape it per hand after loading.

To include matrix dimensions you can mimic the armadillo header when saving in matlab and then use the arma::arma_binary option when loading. If you are interested in that option I can also tell you how to do it.

Upvotes: 2

Martin J.
Martin J.

Reputation: 5118

According to the Armadillo documentation:

file_type can be one of the following:
...
raw_ascii:
Numerical data stored in raw ASCII format, without a header. The numbers are separated by whitespace. The number of columns must be the same in each row. Cubes are loaded as one slice. Data which was saved in Matlab/Octave using the -ascii option can be read in Armadillo, except for complex numbers. Complex numbers are stored in standard C++ notation, which is a tuple surrounded by brackets: eg. (1.23,4.56) indicates 1.24 + 4.56i.

You should therefore be able to load a Matlab matrix written in text format, contained in a file called "MatlabMatrix.mat", by using the following code:

arma::mat fromMatlab;
fromMatlab.load("MatlabMatrix.mat", arma::raw_ascii);

Also, a related question can be found here.

Upvotes: 3

Related Questions