Pages

Sunday, 28 August 2016

Chapter 8 Exercise 6, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*8.6 (Algebra: multiply two matrices) Write a method to multiply two matrices. The header of the method is:

public static double[][] multiplyMatrix(double[][] a, double[][] b)

To multiply matrix a by matrix b, the number of columns in a must be the same as the number of rows in b, and the two matrices must have elements of the same or compatible types. Let c be the result of the multiplication. Assume the column size of matrix a is n. Each element  For example, for two 3 * 3 matrices a and b, c is
where 
 
Write a test program that prompts the user to enter two 3 * 3 matrices and displays their product. Here is a sample run:
Enter matrix1:1 2 3 4 5 6 7 8 9
Enter matrix2:0 2 4 1 4.5 2.2 1.1 4.3 5.2
The matrices are added as follows
1.0      2.0      3.0      0.0    2.0    4.0    5.3 23.9 24.0 
4.0      5.0      6.0   *  1.0    4.5    2.2  = 11.6 56.3 58.2 
7.0      8.0      9.0      1.1    4.3    5.2    17.9 88.7 92.4  
import java.util.Scanner;
 
 
 
public class ProgramingEx8_6 {
 
 public static void main(String[] args) {
  double[][] a = new double[3][3];
  double[][] b = new double[3][3];
  double[][] result;
 
  java.util.Scanner input = new Scanner(System.in);
  System.out.print("Enter matrix1:");
  for (int i = 0; i < a.length; i++) {
   for (int j = 0; j < a[0].length; j++) {
    a[i][j] = input.nextDouble();
   }
 
  }
 
  System.out.print("Enter matrix2:");
  for (int i = 0; i < b.length; i++) {
   for (int j = 0; j < b[0].length; j++) {
    b[i][j] = input.nextDouble();
   }
 
  }
 
  result = multiplyMatrix(a, b);
 
  // printing
  System.out.println("The matrices are added as follows");
  for (int i = 0; i < result.length; i++) {
   for (int j = 0; j < result[0].length; j++) {
 
    System.out.print(a[i][j] + " ");
    if (i == 1 && j == 2) {
     System.out.print("  *  ");
    } else {
     System.out.print("     ");
    }
   }
   for (int j = 0; j < result[0].length; j++) {
    System.out.print(b[i][j] + " ");
    if (i == 1 && j == 2) {
     System.out.print(" = ");
    } else {
     System.out.print("   ");
    }
   }
   for (int j = 0; j < result[0].length; j++) {
    System.out.printf("%.1f ",result[i][j] );
   }
   System.out.println();
  }
 
 }
 
 public static double[][] multiplyMatrix(double[][] a, double[][] b) {
  // Check metrix dimension
  if (a.length != b[0].length)
   return null;
 
  double[][] result = new double[a.length][b[0].length];
 
  for (int i = 0; i < result.length; i++) {
   for (int j = 0; j < result[0].length; j++) {
    for (int n = 0; n < a[0].length; n++) {
     result[i][j] += a[i][n] * b[n][j];
    }
     
   }
 
  }
 
  return result;
 
 }
 
}

No comments :

Post a Comment