Reputation: 1295
I have a Matrix market(.mtx) file. I want a sparse matrix conversion from the matrix market file. Can anyone suggest a way to convert matrix market format to 2 dimensional matrix in c++?
I have tried a matlab approach in converting the matrix market to sparse matrix online. But, I don't succeed in it. It would be of great help if I get a solution in c++. As it helps my project.
Upvotes: 1
Views: 2717
Reputation: 17329
The fast_matrix_market library has a loader that will do exactly what you need:
std::ifstream file("filename.mtx");
std::vector<double> matrix;
int64_t nrows, ncols; // the file's dimensions saved here
fast_matrix_market::read_matrix_market_array(
file,
nrows, ncols,
matrix,
fast_matrix_market::row_major);
That will work with both sparse and dense MatrixMarket files.
Upvotes: 0
Reputation: 1691
There could be several ways to read .mtx data. I just parsed the file and filled the matrix with data. Please find code snippet below :
std::ifstream file("filaname.mtx");
int num_row, num_col, num_lines;
// Ignore comments headers
while (file.peek() == '%') file.ignore(2048, '\n');
// Read number of rows and columns
file >> num_row>> num_col >> num_lines;
// Create 2D array and fill with zeros
double* matrix;
matrix = new double[num_row * num_col];
std::fill(matrix, matrix + num_row *num_col, 0.);.
// fill the matrix with data
for (int l = 0; l < num_lines; l++)
{
double data;
int row, col;
file >> row >> col >> data;
matrix[(row -1) + (col -1) * num_row] = data;
}
file.close();
I hope it helps.
Upvotes: 5
Reputation: 5059
Without more information on your code or goals, it's difficult to say exactly what would would work best. If you're using this format, I'd suggest something similar to this.
Open the file in a std::ifstream
, and then get lines one at a time into a std::string
with std::getline()
for processing. If you know the line has values you want, I would also recommend converting it to std::stringstream
so you can use the >>
operator to extract values.
std::string::find()
lets you determine whether the line you've read is the header. You can convert to stringstream and parse strings out to get information about the file, like "matrix coordinate real general" or others, if you care about these.Or, you could switch to C, which has a library dedicated to Matrix Market I/O.
Upvotes: 1
Reputation: 167
The National Institute of Standards and Technology provides C code that can do the file operations you are looking for. It also has examples of read and write operations in C. Since C code is compatible with C++ you can use this code in the project you are working on. https://math.nist.gov/MatrixMarket/mmio-c.html
Upvotes: 0