reading *.mtx sparse matrix file C++ ,...

How to read *.mtx (http://math.nist.gov/MatrixMarket/formats.html#mtx) file into c++ in visual studio 2010 ?
This should work. If your files don't strictly adhere to the format mentioned in that link, then you may want to do some error checking on the ifstream object.

This requires:
1
2
#include <fstream>
#include <algorithm> 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Open the file:
std::ifstream fin("Matrix.mtx");

// Declare variables:
int M, N, L;

// Ignore headers and comments:
while (fin.peek() == '%') fin.ignore(2048, '\n');

// Read defining parameters:
fin >> M >> N >> L;

// Create your matrix:
double* matrix;			     // Creates a pointer to the array
matrix = new double[M*N];	     // Creates the array of M*N size
std::fill(matrix, matrix + M*N, 0.); // From <algorithm>, zeros all entries.

// Read the data
for (int l = 0; l < L; l++)
{
	int m, n;
	double data;
	fin >> m >> n >> data;
	matrix[(m-1) + (n-1)*M] = data;
}

fin.close();


To use the data in the matrix:
1
2
3
4
5
6
for (int m = 0; m < M; m++)
{
    for(int n = 0; n < N; n++)
        std::cout << matrix[m + n*M] << ' ';
    std::cout << std::endl;
}
Last edited on
Topic archived. No new replies allowed.