/**           Programme to demonstrate matrix multiplication using
 *            two dimesnional arrays.
 *
 *            Note: Matrix manipulation is far better done using
 *                  suitable objects and methods. this program
 *                  is a demonstration of for() loops and NOT the
 *                  recommended (good programming) scheme for 
 *                  matrix manipulation. See next years course
 *                  on how to write the code to allow you to use:
 * 
 *                  Matrix matrixC = matrixA.mult(MatrixB);
 *
 */


public class MatrixMult {
    public static void main(String args[]) {

	int first = 3;
	int second = 4;

	//             Form two matrices 
	//    Note a mathetical matrix is a series of col
	//    vectors. Different from java, so indices are
	//    the opposite way round!!!
	
	double matrixA[][] = new double[second][first];
	double matrixB[][] = new double[first][second];

	//       Fill matrix A and B with random numbers between
	//       0 -> 9. (print out the elemnt values as they are formed)

	System.out.println("Matrix A is:");

	for(int j = 0; j < matrixA.length; j++ ) {
	    for(int i = 0; i < matrixA[j].length; i++) {
		matrixA[j][i] = (int)(10.0*Math.random());
		System.out.print(" " + matrixA[j][i] + " ");
	    }
	    System.out.println();                   // Newline
	}

	
	System.out.println("Matrix B is:");

	for(int j = 0; j < matrixB.length; j++ ) {
	    for(int i = 0; i < matrixB[j].length; i++) {
		matrixB[j][i] = (int)(10.0*Math.random());
		System.out.print(" " + matrixB[j][i] + " ");
	    }
	    System.out.println();                 // Newline
	}

	//      For the space for matrix C to be the product
	//      C = A x B. (of size first by first)

	double matrixC[][] = new double[first][first];


	//      Do the matrix multiple.... note again indices
	//      reversed to what you expect!!! 
	//      Here we need THREE nested loops.

	System.out.println("Matrix C is:");

	for(int j = 0; j < matrixC.length; j++) {
	    for(int i = 0; i < matrixC[j].length; i++) {
		double element = 0.0;                  // Local variable

		//                 Inner most loop to to do the summation

		for(int k = 0; k < matrixA.length; k++) {
		    element += matrixA[k][i]*matrixB[j][k];
		}

		matrixC[j][i] = element;              // Set the element
		System.out.print(" " + matrixC[j][i] + " ");
	    }
	    System.out.println();                    // Newline
	}

    }
}
