0

I'm trying to read and use a matrix market file, but my current attempts haven't produced anything. I'm extremely new to C++ so be gentle. Here's what I've got so far:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream f("GX30.mtx");
int m,n,l;
while(f.peek()=='%') f.ignore(2048, '\n');
f>>m>>n>>l;
cout<<l;
int I[m],J[n],val[l];
int mat[m][n];

for(int i=1;i<=l;i++)
{
    f>>I[i]>>J[i]>>val[i];

}
for(int k=1; k<=l;k++)
{
        mat[I[k]][J[k]]=val[k];
        cout<<"test";
}}

My test output produces nothing, and none of the variables determining the matrix parameters initialize properly. The first few lines from the file I'm reading from are as follows:

%%MatrixMarket matrix coordinate integer general
%% X {5,5} [[30,8,3]] [ (b*a^-1)^3 ]
12 30 60
1 1 1
1 3 1
1 4 1

The first line not proceeded by % indicates the number of rows, then columns, then lastly the number of non zero entries (I think) Then the following lines index the row and column position of each entry, with its corresponding value.

TeeJay
  • 101
  • OT: using `l` as a variable name, you are reducing the readabilty of your code, as it's too easily confused with `1` for most monospace fonts. – Bob__ Oct 23 '17 at 08:37

1 Answers1

0

There are few issues you need to fix.

The main problem is how you access arrays. Array index starts from 0, not 1. Array sizes are different in your application too.

I[m],J[n],val[l];

m, n, l are not equal so you go beyond boundaries of two arrays:

for(int i=1;i<=l;i++)
for(int k=1; k<=l;k++)

You code most likely causes an access violation and crashes, hence you don't even see the result of cout<<l; operation. You shouldn't access all array from a single loop like you do. Something like the following is alright.

for (int i = 0; i < l; ++i)
{
   val[i] ... // val array, not I or J here
}

Also, Matrix Market allows for float values but you are using integers.

Yet another thing: Lines may be separated by "\r", "\n" and "\r\n" but you expect '\n'. Does Matrix Market format specify anything or it relies on OS conventions? If lines are separated with '\r' then your code may not work:

while(f.peek()=='%') f.ignore(2048, '\n');
dmitri
  • 3,183
  • 23
  • 28
  • Opening a file in (the default) text mode will convert the platform’s line ending convention to `'\n'`. – Davis Herring Oct 23 '17 at 02:56
  • @DavisHerring That's not enough [according to this](https://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf) – dmitri Oct 23 '17 at 07:15
  • Fair enough: it works for the execution platform's mode, which is what i said, but this is a good place to consider files "from" other platforms. – Davis Herring Oct 23 '17 at 12:57