Created
September 24, 2015 08:29
-
-
Save temporaer/fec60ccee75676519510 to your computer and use it in GitHub Desktop.
Simple file-format for communicating dense n-dimensional matrices between matlab and C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <numeric> | |
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
#include "boost/multi_array.hpp" | |
template<class T, long unsigned int D=2u> | |
boost::multi_array<T, D> fromfile(std::string f, bool convert_to_c_order=false){ | |
typedef boost::multi_array<T, D> array_type; | |
std::ifstream is(f); | |
static_assert(sizeof(int) == 4, "size of int is not four"); | |
int ndim; | |
is.read((char*)(&ndim), sizeof(int)); | |
assert(D == ndim); | |
std::vector<int> v(ndim); | |
is.read((char*)(&v[0]), ndim*sizeof(int)); | |
boost::array<long unsigned int, D> shape; | |
std::copy(v.begin(), v.end(), shape.begin()); | |
boost::multi_array<float, D> vv(shape, boost::fortran_storage_order()); | |
size_t s = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>()); | |
std::fill(shape.begin(), shape.end(), 0); | |
is.read((char*)(&vv(shape)), s*sizeof(float)); | |
if(convert_to_c_order){ | |
// convert from fortran to C storage order | |
boost::multi_array<float, D> vvv(shape); | |
vvv = vv; | |
//std::cout << (vv.storage_order()==boost::fortran_storage_order()) << "(so)"<<std::endl;; | |
//std::cout << (vvv.storage_order()==boost::fortran_storage_order()) << "(so)"<<std::endl;; | |
return vvv; | |
} | |
return vv; | |
} | |
int main(){ | |
auto vv = fromfile<float, 2>("magic5.bin"); | |
for(int i=0; i<5; i++){ | |
for(int j=0; j<5; j++){ | |
std::printf("%02.0f\t", vv[i][j]); | |
} | |
std::cout << std::endl; | |
} | |
std::cout << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment