Quote:
Originally Posted by sania21
No it does not work if matrix is not a square matrix.
It works only on square matrix.
I want to implement it only on square matrix that can be of any dimension may be 50 by 50 but my coding should be limited.
|
Code:
package matrix;
import java.io.PrintStream;
public class Matrix {
private double matrix[][];
public Matrix(int rows, int cols){
if( rows<1 || cols < 1)
throw new IllegalArgumentException();
matrix = new double[rows][cols];
}
public double get(int p,int q){
return matrix[p][q];
}
public void set(int p,int q, double value){
matrix[p][q] = value;
}
public Matrix invert(){
//if not square - return null
if( matrix.length != matrix[0].length )
return null;
Matrix result = new IMatrix(matrix.length);
/* Starting row - from 0 to last */
for(int startRow = 0; startRow < matrix.length; startRow++){
/* divide all elements in that row on the first one */
double divideOn = matrix[startRow][startRow];
for(int col = startRow; col<matrix[startRow].length; col++){
matrix[startRow][col] = matrix[startRow][col] / divideOn;
result.matrix[startRow][col] = result.matrix[startRow][col] / divideOn;
}
//output
display(System.out);
result.display(System.out);
/* for the rest of the rows: */
for(int currentRow = startRow+1; currentRow < matrix.length; currentRow++){
double multiplier = matrix[currentRow][startRow]; //take the first not 0 value
for(int currentCol = startRow; currentCol<matrix[currentRow].length; currentCol++){
matrix[currentRow][currentCol] = matrix[currentRow][currentCol] - multiplier*matrix[startRow][currentCol];
result.matrix[currentRow][currentCol] = result.matrix[currentRow][currentCol] - multiplier*result.matrix[startRow][currentCol];
}
//output - after each row change
display(System.out);
result.display(System.out);
}
}
return result;
}
public void display(PrintStream ps){
for(double row[] : matrix){
for( double d:row)
ps.print(d+"\t");
ps.println();
}
ps.println();
ps.println();
}
public static void main(String args[]){
Matrix m = new Matrix(3,3);
m.set(0, 0, 4);
m.set(0, 1, 2);
m.set(0, 2, 2);
m.set(1, 0, 4);
m.set(1, 1, 6);
m.set(1, 2, 8);
m.set(2, 0, -2);
m.set(2, 1, 2);
m.set(2, 2, 4);
m.invert().display(System.out);
}
}
class IMatrix extends Matrix{
public IMatrix(int side){
super(side,side);
for( int i=0; i<side;i++){
super.set(i, i, 1.0);
}
}
}
try this one ... I hope it is what you want

Write if something is not ok