next up previous
Next: Example: product of two Up: Unit 07 Previous: Example: printing out the

Example: sum of two matrices

We develop a static method, matrixSum, that takes as parameters two matrices A and B of doubles, and returns a new matrix obtained by summing corresponding elements of A and B. We assume that A and B have the same dimensions (i.e., the same number of rows and the same number of columns).

public static double[][] matrixSum(double[][] A, double[][] B) {
  double[][] C = new double[A.length][A[0].length];
  for (int i = 0; i < A.length; i++)
    for (int j = 0; j < A[0].length; j++)
      C[i][j] = A[i][j] + B[i][j];
  return C;
}

Note that, in order to access all elements of the matrices A and B, we use two nested for loops: the outermost one iterates over the rows (i), while the innermost one iterates over the elements of each row (j).

Example of usage:

public static void main(String[] args) {
  double[][] A = {           // creates matrix A of dimension 2x3
    { 1.2, 2.3, 2.3 },       // row 0 of A (array of 3 double)
    { 7.4, 5.1, 9.8 }        // row 1 of A (array of 3 double)
  };
  double[][] B = {           // creates matrix B of dimension 2x3
    { 5.0, 4.0, 1.3 },       // row 0 of B (array of 3 double)
    { 1.2, 0.3, 3.2 }        // row 1 of B (array of 3 double)
  };

  double[][] C = matrixSum(A,B);   // calculates the sum of A and B
  System.out.println(C[1][0]);       // prints out 8.6
}


next up previous
Next: Example: product of two Up: Unit 07 Previous: Example: printing out the