Question

In: Computer Science

Lab # 4 Multidimensional Arrays Please write in JAVA. Programming Exercise 8.5 (Algebra: add two matrices)...

Lab # 4 Multidimensional Arrays

Please write in JAVA.

Programming Exercise 8.5 (Algebra: add two matrices)

Write a method to add two matrices. The header of the method is as follows:

public static double[][] addMatrix(double[][] a, double[][] b

In order to be added, the two matrices must have the same dimensions and the same or compatible types of elements. Let c be the resulting matrix. Each element cij is aij + bij. For example, for two 3 * 3 matrices a and b, c is

Write a test program that prompts the user to enter two 3 * 3 matrices and displays their sum. Here is a sample run

Programming Exercise 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 cij is ai1 * b1j + ai2 * b2j + c + ain * bnj. For example, for two 3 * 3 matrices a and b, c is

where cij = ai1 * b1j + ai2 * b2j + ai3 * b3j. Write a test program that prompts the user to enter two 3 * 3 matrices and displays their product. Here is a sample run:

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Program1.java (code for Exercise 8.5)

import java.util.Scanner;

public class Program1 {

      // required method to add two matrices

      public static double[][] addMatrix(double[][] a, double[][] b) {

            if (a.length != b.length || a[0].length != b[0].length) {

                  return null; // cannot be added

            }

            // creating a matrix to store results

            double[][] result = new double[a.length][a[0].length];

            // looping and adding corresponding elements and saving to result

            for (int i = 0; i < a.length; i++) {

                  for (int j = 0; j < a[0].length; j++) {

                        result[i][j] = a[i][j] + b[i][j];

                  }

            }

            return result;

      }

      // a helper method defined to read elements to a matrix

      static void readMatrix(double matrix[][]) {

            Scanner scanner = new Scanner(System.in);

            for (int i = 0; i < matrix.length; i++) {

                  for (int j = 0; j < matrix[0].length; j++) {

                        matrix[i][j] = scanner.nextDouble();

                  }

            }

      }

      // a helper method defined to print elements of a matrix

      static void printMatrix(double matrix[][]) {

            for (int i = 0; i < matrix.length; i++) {

                  for (int j = 0; j < matrix[0].length; j++) {

                        System.out.print(matrix[i][j] + " ");

                  }

                  System.out.println();

            }

      }

      public static void main(String[] args) {

            // creating two matrices

            double a[][] = new double[3][3];

            double b[][] = new double[3][3];

            // asking and reading two matrices

            System.out.println("Enter first matrix (3x3)");

            readMatrix(a);

            System.out.println("Enter second matrix (3x3)");

            readMatrix(b);

            // finding sum

            double c[][] = addMatrix(a, b);

            // displaying resultant matrix

            System.out.println("\nSum of two matrices:");

            printMatrix(c);

      }

}

// Program2.java (code for Exercise 8.6)

import java.util.Scanner;

public class Program2 {

      // required method to multiply two matrices

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

            // finding rows and columns count for both matrices

            int row1 = a.length;

            int col1 = a[0].length;

            int row2 = b.length;

            int col2 = b[0].length;

            if (col1 != row2) {

                  // multiplication not possible

                  return null;

            }

            // creating a row1 x col2 matrix for storing the result

            double result[][] = new double[row1][col2];

            //looping and multiplying the matrix

            for (int i = 0; i < row1; i++) {

                  for (int j = 0; j < col2; j++) {

                        for (int k = 0; k < col1; k++) {

                              result[i][j] += a[i][k] * b[k][j];

                        }

                  }

            }

            return result;

      }

      // a helper method defined to read elements to a matrix

      static void readMatrix(double matrix[][]) {

            Scanner scanner = new Scanner(System.in);

            for (int i = 0; i < matrix.length; i++) {

                  for (int j = 0; j < matrix[0].length; j++) {

                        matrix[i][j] = scanner.nextDouble();

                  }

            }

      }

      // a helper method defined to print elements of a matrix

      static void printMatrix(double matrix[][]) {

            for (int i = 0; i < matrix.length; i++) {

                  for (int j = 0; j < matrix[0].length; j++) {

                        System.out.print(matrix[i][j] + " ");

                  }

                  System.out.println();

            }

      }

      public static void main(String[] args) {

            // creating two matrices

            double a[][] = new double[3][3];

            double b[][] = new double[3][3];

            // asking and reading two matrices

            System.out.println("Enter first matrix (3x3)");

            readMatrix(a);

            System.out.println("Enter second matrix (3x3)");

            readMatrix(b);

            // finding product

            double c[][] = multiplyMatrix(a, b);

            // displaying resultant matrix

            System.out.println("\nProduct of two matrices:");

            printMatrix(c);

      }

}

//OUTPUT OF BOTH PROGRAMS

Enter first matrix (3x3)

1 2 3

4 5 6

7 8 9

Enter second matrix (3x3)

1 2 3

4 5 6

7 8 9

Sum of two matrices:

2.0 4.0 6.0

8.0 10.0 12.0

14.0 16.0 18.0

Enter first matrix (3x3)

1 2 3

4 5 6

7 8 9

Enter second matrix (3x3)

1 1 2

3 3 4

0 0 1

Product of two matrices:

7.0 7.0 13.0

19.0 19.0 34.0

31.0 31.0 55.0


Related Solutions

Write C program Multidimensional Arrays Design a program which uses two two-dimensional arrays as follows: an...
Write C program Multidimensional Arrays Design a program which uses two two-dimensional arrays as follows: an array which can store up to 50 student names where a name is up to 25 characters long an array which can store marks for 5 courses for up to 50 students The program should first obtain student names and their corresponding marks for a requested number of students from the user. Please note that the program should reject any number of students that...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same nodes, etc. Write the main method to test the swapNodes method. Hint: You may need to traverse the list. Exercise 2 In this exercise, you will...
Lab 1 Write a program in the C/C++ programming language to input and add two fractions...
Lab 1 Write a program in the C/C++ programming language to input and add two fractions each represented as a numerator and denominator. Do not use classes or structures. Print your result (which is also represented as a numerator/denominator) to standard out. If you get done early, try to simplify your result with the least common denominator. The following equation can be used to add fractions: a/b + c/d = (a*d + b*c)/(b*d) Example: 1/2 + 1/4 = ( 1(4)...
C++ PROGRAM Programming Exercise 11 in Chapter 8explains how to add large integers using arrays. However,...
C++ PROGRAM Programming Exercise 11 in Chapter 8explains how to add large integers using arrays. However, in that exercise, the program could add only integers of, at most, 20 digits. This chapter explains how to work with dynamic integers. Design a class named largeIntegers such that an object of this class can store an integer of any number of digits. Add operations to add, subtract, multiply, and compare integers stored in two objects. Also add constructors to properly initialize objects...
java programming write a program with arrays to ask the first name, last name, middle initial,...
java programming write a program with arrays to ask the first name, last name, middle initial, IDnumber and 3 test scores of 10 students. calculate the average of the 3 test scores. show the highest class average and the lowest class average. also show the average of the whole class. please use basic codes and arrays with loops the out put should look like this: sample output first name middle initial last name    ID    test score1 test score2...
JAVA programming language Please add or modify base on the given code Adding functionality Add functionality...
JAVA programming language Please add or modify base on the given code Adding functionality Add functionality for multiplication (*) Adding JUnit tests Add one appropriately-named method to test some valid values for tryParseInt You will use an assertEquals You'll check that tryParseInt returns the expected value The values to test: "-2" "-1" "0" "1" "2" Hint: You will need to cast the return value from tryParseInt to an int e.g., (int) ValidationHelper.tryParseInt("1") Add one appropriately-named method to test some invalid...
Java Programming Activity Description: This lab requires you to simulate the rolling of two dice. Two...
Java Programming Activity Description: This lab requires you to simulate the rolling of two dice. Two dice consisting of 6 sides are rolled. Write a program that simulates this. The user will be asked if he/she wishes to continue the roll of dice. If the answer is, “Y” or “y”, then your application will continue to roll the two dice. Each roll of the dice must occur 6 times, each time the user agrees to continue (see sample output). Use...
This is for Java programming. Please use ( else if,) when writing the program) Write a...
This is for Java programming. Please use ( else if,) when writing the program) Write a java program to calculate the circumference for the triangle and the square shapes: The circumference for: Triangle = Side1 + Side2 +Sid3 Square = 4 X Side When the program executes, the user is to be presented with 2 choices. Choice 1 to calculate the circumference for the triangle Choice 2 to calculate the circumference for the square Based on the user's selection the...
Write a C function to add the elements of two same-sized integer arrays and return ptr...
Write a C function to add the elements of two same-sized integer arrays and return ptr to a third array. int *addTwoArrays(int *a1, int *b1, int size); The function should follow the following rules: If the sum for any element is negative, make it zero. If a1 and b1 point to the same array, it returns a NULL If any input array is NULL, it returns a NULL. Please call this function with the following arrays and print the sums...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT