I have a multi-dimensional matrix in Matlab, I save it as a binary file like this:
mat = reshape(1:90, 9,5,2);
fileName = 'mat.bin';
fid = fopen(fileName, 'w');
fwrite(fid, mat, 'int32');
fclose(fid);
In C++ I load it like this:
struct Mat {
int32_t arr[9][5][2];
};
std:ifstream input("mat.bin");
Mat* m = new Mat();
input.read(reinterpret_cast<char*>(m), sizeof(Mat));
input.close();
The problem is that the loaded data is not arranged the same way in memory for instance:
Accessing arr[1][1][1] will yield the value of the Matlab's array of indices mat(5,2,1)
(considering of course that Matlab's indices start at 1)
How can I arrange the matrix (and any other multi-dimensional matrix) before writing it to a binary file, in a way that arr[i][j][k] will be the same as mat(i+1, j+1, k+1)?
EDIT :
Current solution
For the 2-D case, Transpose of matrix solves it.For x-D I found that I can change the order of vectors like this
permute(mat, [D D-1 D-2 ... 1])so it's like spreading the vectors (which matches how memory is mapped in C++) I still look for a more general code that doesn't have to write a vector of dimensions (which sometimes change)
Thanks.