Advertisement
Guest User

MatrixInverse

a guest
Oct 1st, 2014
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3.  
  4. public class MatrixInverse {
  5.     /*
  6.      *
  7.      * Luis Quinones
  8.      * Assignment 5
  9.      * Professor Silvestri
  10.      *
  11.      * Returns the inverse matrix of a given matrix
  12.      *
  13.      */
  14.    
  15.     public static double [][] inverse (double [][] A){
  16.         double determinant = determinant(A);
  17.         if(determinant==0)
  18.             return null;
  19.         else {
  20.            
  21.        
  22.         double [][] inverse = {
  23.                 {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]},
  24.                 {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]},
  25.                 {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]}   
  26.         };
  27.        
  28.         for (int i=0;i<inverse.length;i++){
  29.             for(int j =0; j<inverse[i].length;j++)
  30.             {
  31.                 inverse[i][j]/=determinant;            
  32.             }
  33.         }
  34.         return inverse;    
  35.     }
  36.     }
  37.    
  38.     public static double determinant(double [][] A){   
  39.         return 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];               
  40.     }
  41.    
  42.     public static double [][] getInput()
  43.     {
  44.          Scanner sc = new Scanner(System.in);  
  45.          System.out.print("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: ");
  46.         double [][] A = new double[3][3];
  47.         for(int i=0; i<3;i++){
  48.             for(int j=0; j<3; j++)
  49.             {
  50.                 A[i][j] = sc.nextDouble();         
  51.             }      
  52.         }
  53.         return A;  
  54.     }
  55.    
  56.     public static void printArray(double [][] A){
  57.        
  58.         for(int i=0;i<A.length;i++){
  59.             for(int j=0;j<A[i].length;j++)
  60.                 System.out.print(A[i][j]+" ");
  61.             System.out.println("");
  62.         }  
  63.     }
  64.     public static void main(String args[]){
  65.         double [][]A = getInput();
  66.         double [][]inverse = inverse(A);
  67.        
  68.         if(inverse==null)
  69.             System.out.println("No inverse matrix");
  70.         else
  71.             printArray(inverse);   
  72.     }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement