Ojalgo - Load Matrix from CSV

Viewed 67

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 Answers

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.

Related