Wednesday, 28 August 2013

Determinant and Transpose of a square matrix using Java...

NOTE- Here matrix is input through a file.

here is the code .....


       

import java.io.*;
import java.util.*;
import static java.lang.Math.pow;

public class Read {


 static Scanner input = new Scanner(System.in);

 static int count = 0;
 public static void main(String[] args) throws IOException {
  String fileName = "test.txt";
  File file = new File("test.txt");
  BufferedReader be = new BufferedReader(new FileReader(file));
  String raw;
  while ((raw = be.readLine()) != null)
   count++;

  int[][] transpose = new int[count][count];
  int[][] matrix = new int[count][count];





  String line = "";

  FileInputStream inputStream = new FileInputStream(fileName);
  Scanner scanner = new Scanner(inputStream);
  DataInputStream in = new DataInputStream(inputStream);
  BufferedReader bf = new BufferedReader(new InputStreamReader( in ));

  int lineCount = 0;
  String[] numbers;
  while ((line = bf.readLine()) != null) {
   numbers = line.split(" ");
   for (int i = 0; i < 3; i++) {
    matrix[lineCount][i] = Integer.parseInt(numbers[i]);
   }

   lineCount++;
  }
  bf.close();
  System.out.println("The matrix is:");

  for (int i = 0; i < 3; i++) {
   for (int j = 0; j < 3; j++) {
    System.out.print(matrix[i][j] + " ");
   }
   System.out.println();
  }
  System.out.println();


  for (int k = 0; k < count; k++) {
   for (int k1 = 0; k1 < count; k1++) {
    transpose[k][k1] = matrix[k1][k];

   }
  }

  int i, j = 1, k = count - 1;
  double determinant = 0.0, p;
  for (i = 0; i < count; i++) {
   p = Math.pow(-1.0, i);
   if (i == count - 1)
    k = 1;
   determinant = determinant + (matrix[0][i] * (matrix[1][j] * matrix[2][k] - matrix[2][j] * matrix[1][k])) * p;
   j = 0;

  }
  System.out.println(determinant);

 }
}

       
 

No comments:

Post a Comment