001package edu.pdx.cs410J.rmi;
002
003import java.io.*;
004import java.text.*;
005
006/**
007 * Represents a matrix of <code>double</code>s.  Contains methods to
008 * create special matrices for this assignment.  It also contains
009 * general methods to multiply matrices.
010 *
011 * @author David Whitlock
012 */
013public class Matrix {
014  private static NumberFormat format;
015
016  static {
017    format = NumberFormat.getNumberInstance();
018  }
019
020  /**
021   * Sets the number of decimal places to be displayed.
022   */
023  public static void setPrecision(int n) {
024    format.setMinimumFractionDigits(n);
025  }
026
027  /**
028   * Returns the number of rows in a matrix
029   */
030  public static int countRows(double[][] m) {
031    return m.length;
032  }
033
034  /**
035   * Returns the number of columns in a matrix
036   *
037   * @throws IllegalArgumentException
038   *         The columns are not length-consistent
039   */
040  public static int countColumns(double[][] m) {
041    int count = m[0].length;
042    for (int i = 1; i < m.length; i++) {
043      if (m[i].length != count) {
044        String s = "The matrix is not length-consistent (" +
045          m[i].length + " != " + count + ")";
046        throw new IllegalArgumentException(s);
047      }
048    }
049    return count;
050  }
051
052  /**
053   * Multiplies two matrices and returns their product.
054   */
055  public static double[][] multiply(double[][] a, double[][] b) {
056    // Make sure the matrices can be multiplied
057    int aRows = countRows(a);
058    int aColumns = countColumns(a);
059    int bRows = countRows(b);
060    int bColumns = countColumns(b);
061
062    if(aColumns != bRows) {
063      throw new
064        IllegalArgumentException("Matrices cannot be multiplied");
065    }
066
067    int n = aColumns;
068
069    // a x b = c
070    double[][] c = new double[aRows][bColumns];
071    for(int i = 0; i < aRows; i++) {
072      for(int j = 0; j < bColumns; j++) {
073        double sum = 0.0;
074        for(int k = 0; k < n; k++) {
075          sum += a[i][k] * b[k][j];
076        }
077        c[i][j] = sum;
078      }
079    }
080
081    return(c);
082  }
083
084  /**
085   * Prints this a matrix
086   */
087  public static void print(String name, double[][] m, PrintWriter out) {
088    out.println("Matrix " + name + ":");
089    for(int i = 0; i < countRows(m); i++) {
090      out.print("  ");
091      for(int j = 0; j < countColumns(m); j++) {
092        out.print(format.format(m[i][j]) + " ");
093      }
094      out.println("");
095    }
096  }
097
098  /**
099   * Prints a vector in column form
100   */
101  public static void print(String name, double[] v, PrintWriter out) {
102    out.println("Vector " + name + ":");
103    for (int i = 0; i < v.length; i++) {
104      out.println("  " + format.format(v[i]) + " ");
105    }
106  }
107
108}