Matrix Cross Product Java Code

I had a ton of trouble finding matrx/matrix corss product code, but only found stuff for matricies.  Even common matrix packages like JAMA didn’t have it, so I’m reproducing it here in case I, or anyone else, ever needs it.

/**
* the cross product of a & b storing in result
*/

public static void product(Matrix a, Matrix b, MutableMatrix result) throws Matrix.WrongDimensionException {
     int rca = a.getRowCount();
     int cca = a.getColumnCount();
     int rcb = b.getRowCount();
     int ccb = b.getColumnCount();

     if (cca != rcb)
           throw new Matrix.WrongDimensionException("column count of matrix a = " + cca + ", row count of matrix b = " + rcb);
          result.setDimension(rca, ccb);

          for (int r = 0; r < rca; r++) {
               for (int c = 0; c < ccb; c++) {
                    double sum = 0;
                    for (int i = 0; i < cca; i++) {
                           sum += a.getElement(r, i) * b.getElement(i, c);
                   }
                   result.setElement(r, c, sum);
             }
         }
    }
}

Leave a Comment