Transfer Sparse Matrix From C++ To Matlab
It happens that your C++ code solves large sparse linear systems that involve large sparse matrices. Debugging such code is a be-yotch. Only super-brained engineers can spot hidden errors in matrices that are displayed as an unformatted array of numbers. And even for them it’s an inconvenient affair. But not to worry. Matlab gladly helps us displaying any matrix in many wonderful ways.
First, we need some mechanism to render the matrix into a file. Let A be a sparse matrix. We open a file file, iterate over all values in A, and write every item sItem with preceding row and column number into a new line:
1 2 3 4 5 6 7 8 9 10 11 12 13 | QFile *file = OpenFileWriteOnly("A.txt"); if (file != NULL) { SparseRowMatrix::const_iterator it; for (it = A.begin(); it != A.end(); it++) { QString sItem = QString::number(it.data()); QString sLine; sLine.sprintf("%d %d %s \n", it.row(), it.col(), sItem.toAscii().data()); file.write(sLine.toAscii()); } CloseFile(file); } |
Second, we load the matrix into matlab using the following code:
And third, voilĂ , you can use your all time favorite matlab methods to analyse the sh*t out of A. If you have no favorite one, try
1 | >> spy(A) |
Wow, this matrix surely looks odd…
C++, export, import, Matlab, matrix, sparse, spy