package com.imsl.test.example.math; import com.imsl.math.*; import java.io.*; /** *

* SparseMatrix Example 2: Converts a matrix in market format to a sparse matrix * format. *

* The matrix market exchange format is an ASCII file format that represents * sparse matrices in coordinate format. It consists of three sections: The * header section is the first line in the file and contains general information * about the matrix, e.g. data type and symmetry properties. This line is * followed by the comments section which consists of zero or more lines of * comments. The remainder of the file is the data section. The first line of * the data section contains the row number, column number, and number of * nonzeros of the matrix. The following lines contain the location and value of * all nonzero entries of the matrix, usually one per line. A file in Matrix * Market format is read and converted to a JMSL SparseMatrix in this example. * Matrix information and the one norm of the matrix are printed. * * @see Code * @see Output */ public class SparseMatrixEx2 { /** * Reads a file containing Market format data. */ public static class MTXReader { private String typecode; private SparseMatrix matrix; /** * Reads a file. * * @param filename a String, the name of the file * @throws java.io.IOException */ public void read(String filename) throws java.io.IOException { try (InputStream s = SparseMatrixEx2.class.getResourceAsStream(filename)) { BufferedReader br = new BufferedReader(new InputStreamReader(s)); // read type code initial line String line = br.readLine(); typecode = line; // read comment lines if any boolean comment = true; while (comment) { line = br.readLine(); comment = line.startsWith("%"); } // line now contains the size information which needs to be parsed String[] str = line.split("( )+"); int nRows = Integer.valueOf(str[0].trim()); int nColumns = Integer.valueOf(str[1].trim()); // now we're into the data section matrix = new SparseMatrix(nRows, nColumns); while (true) { line = br.readLine(); if (line == null) { break; } str = line.split("( )+"); int i = Integer.valueOf(str[0].trim()); int j = Integer.valueOf(str[1].trim()); double x = Double.valueOf(str[2].trim()); matrix.set(i - 1, j - 1, x); } br.close(); } } public String getTypeCode() { return this.typecode; } } public static void main(String args[]) throws Exception { MTXReader mr = new MTXReader(); mr.read("bcsstk01.mtx"); SparseMatrix A = mr.matrix; // Print the matrix type System.out.println("The matrix type is " + mr.getTypeCode()); // Print the matrix information and its one norm System.out.println("The number of rows is " + A.getNumberOfRows()); int ncols = A.getNumberOfColumns(); System.out.println("The number of columns is " + ncols); long nnz = A.getNumberOfNonZeros(); System.out.println("The number of nonzero elements is " + nnz); System.out.println(); System.out.println("The 1 norm of the matrix is " + A.oneNorm()); } }