Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Name : Kyle Blanchard
- // Due : 10/1/2014
- // Class : CSCI-401
- // Assignment : Matrix Inverse ~ Homework # 5
- // Contact : Kwblanchard@student.stcc.edu
- // package csci401;
- import java.util.Scanner;
- public class Homework5 {
- public static void main(String[] args) {
- @SuppressWarnings("resource")
- Scanner input = new Scanner(System.in);
- System.out.print("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: ");
- // Assigns the user entered values to a 3x3 Matrix called A
- double[][] A = new double[3][3];
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- A[i][j] = input.nextDouble();
- }
- }
- // Gets the inverse of Matrix A
- double[][] Ainverse = inverse(A);
- // If there is no inverse matrix display the message saying so. If there is a matrix, print it.
- if (Ainverse == null)
- System.out.println("Unable to create an inverse matrix!");
- else
- displayInverse(Ainverse);
- }
- public static double[][] inverse(double[][] A) {
- // Gets the value of the Determinate using the formula aei+_bfg-cdh-ceg-bdi-afh
- double determinant = (A[0][0] * A[1][1] * A[2][2]) + (A[2][0] * A[0][1] * A[1][2]) + (A[0][2] * A[1][0] * A[2][1]) - (A[0][2] * A[1][1] * A[2][0]) - (A[0][0] * A[1][2] * A[2][1]) - (A[2][2] * A[1][0] * A[0][1]);
- if (determinant == 0)
- return null;
- else {
- // Gets the Inverse matrix of Matrix A using the given formula
- double[][] inverse = {
- { A[1][1] * A[2][2] - A[1][2] * A[2][1], A[0][2] * A[2][1] - A[0][1] * A[2][2], A[0][1] * A[1][2] - A[0][2] * A[1][1] },
- { A[1][2] * A[2][0] - A[1][0] * A[2][2], A[0][0] * A[2][2] - A[0][2] * A[2][0], A[0][2] * A[1][0] - A[0][0] * A[1][2] },
- { A[1][0] * A[2][1] - A[1][1] * A[2][0], A[0][1] * A[2][0] - A[0][0] * A[2][1], A[0][0] * A[1][1] - A[0][1] * A[1][0] } };
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- inverse[i][j] = ( inverse[i][j] / determinant ) ;
- }
- }
- return inverse;
- }
- }
- public static void displayInverse(double[][] A) {
- // Prints each character of the inverse matrix followed by a space and a line break every 3 characters
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++)
- System.out.print(A[i][j] + " ");
- System.out.println("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement