class Mat2 { // Five ways to store the 2x2 matrix data. double a00, a01, a10, a11; // very fast double[] a = new double[4]; // good for large matrices double[] r1 = new double[2]; // row vectors double[] r2 = new double[2]; double[] c1 = new double[2]; // column vectors double[] c2 = new double[2]; // mathematically accurate double[][] a = new double[2][2]; // Not good for matrices! // Two ways to implement matrix multiplication. Matrix mult(Matrix m) // does mutating { // do the calculation mutating this object return this; // for chaining } Matrix tims(Matrix m) // does an allocation { return new Matrix( has the calculated data in it ); } } m1.mult(m2).mult(m3); // chained methods don't compile if mult() is a void method // m4 = m1 * m2 // m5 = m1 * m3 m4 = m1.mult(m2); m5 = m1.mult(m3); // WRONG // We need to do the following (if mult() allows chaining). m4 = Identity().mult(m1).mult(m2); // need to allocate an identity matrix m5 = Identity().mult(m1).mult(m3); // If mult() is a void method, then we need to do the following steps. m4 = Identity(); m4.mult(m1); m4.mult(m2); m5 = Identity(); m5.mult(m1); m5.mult(m3); Memory allocation for each kind of matrix storage. Matrix +----------+ | a00 a01 | | a10 a11 | +----------+ Matrix +----------+ double[4] | +----+ | +---+---+---+---+ | a| ---|--|----->| | | | | | +----+ | +---+---+---+---+ +----------+ Matrix +----------+ double[2] | +----+ | +---+---+ |r1| ---|--|----->| | | | +----+ | +---+---+ | | | +----+ | +---+---+ |r2| ---|--|----->| | | | +----+ | +---+---+ +----------+ Matrix +----------+ double[2] | +----+ | +---+---+ |c1| ---|--|----->| | | | +----+ | +---+---+ | | | +----+ | +---+---+ |c2| ---|--|----->| | | | +----+ | +---+---+ +----------+ Matrix +----------+ double[2][] double[2] | +----+ | +-----+ +---+---+ | a| ---|--|----->| ----|--------->| | | | +----+ | +-----+ +---+---+ +----------+ | ----|----+ +-----+ | double[2] | +---+---+ +---->| | | +---+---+