2

I have some large headered CSV file that contains values I would like to load into a Matrix.

I have come across the LineSplittingParser class but cannot find good examples on how to use this to actually get a Matrix object from a file.

Could anyone give a small example of how to achieve this?

1 Answers1

1

Not sure LineSplittingParser is a good alternative to read matrices, but something like this may work:

File fileToParse = null;
// You have to know the number of rows and columns
int numRows = 9, numCols = 9;

Primitive64Store matrix = Primitive64Store.FACTORY.make(numRows, numCols);

LineSplittingParser parser = new LineSplittingParser("\\s+", true);

AtomicInteger row = new AtomicInteger();

boolean skipHeader = true;

parser.parse(fileToParse, skipHeader, line -> {

    int i = row.intValue();

    for (int j = 0; j < line.length; j++) {
        matrix.set(i, j, Double.parseDouble(line[j]));
    }

    row.incrementAndGet();
});

This code is not tested – it's just an outline – and you'll have to replace "\\s+" with whatever separator is used in your files.

apete
  • 1,250
  • 1
  • 10
  • 16
  • If there is a better method than the LineSplittingParser I will gladly hear it. Especially considering i won't know the amount of collumns and rows ahead of time. – Dr. Njitram Nov 09 '20 at 19:08