Computer Science 252
Problem Solving with Java

Fall 2013, The College of Saint Rose

Matrix2D BlueJ Project

Click here to download a BlueJ project for Matrix2D.


Matrix2D Source Code

The Java source code for Matrix2D is below. Click on a file name to download it.


Matrix2D.java

/*
 * Example Matrix2D
 *
 *  A class representing a 2D square matrix with some methods to manipulate
 *  such matrices.
 *  
 * Jim Teresco, The College of Saint Rose, CSC 252, Fall 2013
 *
 * $Id: Matrix2D.java 2268 2013-11-30 22:37:49Z terescoj $
 */

import java.util.Random;

public class Matrix2D {
    
    // the actual matrix data storage, space to be allocated by the constructor
    private double [][] data;
    
    // a basic constructor to allocate but not otherwise initialize a matrix, so
    // by the rules of Java, all entries are initially 0.0.
    public Matrix2D(int size) {
        
        data = new double[size][size];
    }
    
    // initialize the entries randomly within a range
    public void randomInit(double low, double high) {
        
        Random r = new Random();
        
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data.length; col++) {
                data[row][col] = r.nextDouble() * (high-low) + low;
            }
        }      
    }

    // make this the identity matrix
    public void setToIdentity() {
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data.length; col++) {
                if (row == col) {
                    data[row][col] = 1.0;
                }
                else {
                    data[row][col] = 0.0;
                }
            }
        }      
       
    }
    
    // element mutator, will throw an exception of the row or column is not
    // within the correct range.
    public void set(int row, int col, double value) 
        throws Matrix2DIndexOutOfBoundsException {
        
        if (row < 0 || row >= data.length) {
            throw new Matrix2DIndexOutOfBoundsException("Row", row, data.length);
        }

        if (col < 0 || col >= data.length) {
            throw new Matrix2DIndexOutOfBoundsException("Column", col, data.length);
        }
        
        data[row][col] = value;
    }

    // element accessor, again will throw an exception if bad values are passed for
    // row/col.
    public double get(int row, int col) 
        throws Matrix2DIndexOutOfBoundsException {
        
        if (row < 0 || row >= data.length) {
            throw new Matrix2DIndexOutOfBoundsException("Row", row, data.length);
        }

        if (col < 0 || col >= data.length) {
            throw new Matrix2DIndexOutOfBoundsException("Column", col, data.length);
        }
        
        return data[row][col];
    }

    // compare two matrices for equality -- must be the same size then elementwise equal.
    // note that we must take a parameter of type Object to override the builtin equals method.
    public boolean equals(Object other) {
    
        Matrix2D o = (Matrix2D) other;
        
        if (data.length != o.data.length) return false;
        
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data.length; col++) {
                if (data[row][col] != o.data[row][col]) return false;
            }
        }
        
        return true;
    }
    
    // print the matrix in a nice format
    public String toString() {
        
        // use a StringBuffer to build up an answer more efficiently
        StringBuffer sb = new StringBuffer();
        
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data.length; col++) {
                sb.append(data[row][col]);
                if (col != data.length-1) sb.append(" ");
            }
            sb.append("\n");
        }
     
        return sb.toString();
    }
    
    // nondestructive matrix-matrix add, which will throw an exception
    // if the sizes do not match up (making the addition impossible).
    // if all is well, we do an elementwise addition to create and return
    // a brand new Matrix2D object that contains the sum of this and other.
    public Matrix2D add(Matrix2D other) throws Matrix2DSizeMismatchException {
        
        if (data.length != other.data.length) {
            throw new Matrix2DSizeMismatchException(data.length, other.data.length);
        }
        
        Matrix2D result = new Matrix2D(data.length);
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data.length; col++) {
                result.data[row][col] = data[row][col] + other.data[row][col];
            }
        }
     
        return result;
    }
    
    // a main method that tries out some of the matrix operations here
    public static void main(String[] args) throws Matrix2DSizeMismatchException,
        Matrix2DIndexOutOfBoundsException {
    
        Matrix2D a = new Matrix2D(4);
        
        System.out.println("Uninitialized 4x4 matrix a");
        System.out.println(a);
        
        a.randomInit(0, 10);
        System.out.println("4x4 matrix a after random initialization 0-10");
        System.out.println(a);
        
        // set a value in a
        try {
            a.set(2, 2, 0);
        }
        catch (Exception e) {
            System.err.println(e);
        }

        System.out.println("4x4 matrix a after a[2][2] is set to 0");
        System.out.println(a);
        
        // try to get a value out of range
        try {
            double x = a.get(7, 2);
        }
        catch (Exception e) {
            System.err.println(e);
        }
        
        Matrix2D ident = new Matrix2D(3);
        ident.setToIdentity();
        System.out.println("3x3 identity matrix");
        System.out.println(ident);
        
        System.out.println("Checking if a.equals(a): " + a.equals(a));
        System.out.println("Checking if a.equals(ident): " + a.equals(ident));
        
        Matrix2D b = new Matrix2D(4);
        b.randomInit(-100, 100);
        System.out.println("4x4 matrix b after random initialization -100 to 100");
        System.out.println(b);
        
        Matrix2D c = a.add(b);
        System.out.println("4x4 matrix c=a+b");
        System.out.println(c);
        
        // finally, we'll try a mismatched size add and not catch the exception
        Matrix2D d = c.add(ident);
                
    }
}

Matrix2DSizeMismatchException.java


/**
 * An exception to indicate that two Matrix2D objects are not the same size when
 * that is required.
 * 
 * @author Jim Teresco
 * 
 * $Id: Matrix2DSizeMismatchException.java 2268 2013-11-30 22:37:49Z terescoj $
 */
public class Matrix2DSizeMismatchException extends Exception
{

    public Matrix2DSizeMismatchException(int size1, int size2) {
        
        super("Matrix2D size mismatch: " + size1 + "!=" + size2);
    }
}

Matrix2DIndexOutOfBoundsException.java


/**
 * An exception to be thrown by Matrix2D methods when a row or column
 * index is specified out of range.
 * 
 * @author Jim Teresco
 * 
 * $Id: Matrix2DIndexOutOfBoundsException.java 2268 2013-11-30 22:37:49Z terescoj $
 */
public class Matrix2DIndexOutOfBoundsException extends Exception
{
    public Matrix2DIndexOutOfBoundsException(String rowCol, int number, int size) {
        
        super("Matrix2D " + rowCol + " " + number + " must be in range 0-" + (size-1));
    }
}