javamatrixlogicjama

How to print non symmetric value while using for loop in Java


I want to implement a matrix using for loop. To create the matrix I used Jama Matrix Package.

Here is my code

import Jama.Matrix;

public class Matrixnonsym {

   public static void main(String args[]) {
       Matrix Mytest=new Matrix(5,5);
       for(int i=0; i<4; i++) {
           Mytest.set(i,i,1);
           Mytest.set(i+1,i,1);
       }
       Mytest.print(9,6);
   }
}

Here is my output:

1.000000   0.000000   0.000000   0.000000   0.000000
1.000000   1.000000   0.000000   0.000000   0.000000
0.000000   1.000000   1.000000   0.000000   0.000000
0.000000   0.000000   1.000000   1.000000   0.000000
0.000000   0.000000   0.000000   1.000000   0.000000

There is no compilation error or runtime error. The difficulty is that how could I make the (0,0) cell value 2? As this matrix constructed using for loop so all value constructed symmetrically. Then how could I make only one cell with different value?

Desire Output:

2.000000   0.000000   0.000000   0.000000   0.000000
1.000000   1.000000   0.000000   0.000000   0.000000
0.000000   1.000000   1.000000   0.000000   0.000000
0.000000   0.000000   1.000000   1.000000   0.000000
0.000000   0.000000   0.000000   1.000000   0.000000

Solution

  • You can use a if condition inside the for loop to have a different value for the particular cell.

    import Jama.Matrix;
    
    public class Matrixnonsym {
    public static void main(String args[]){
         Matrix Mytest=new Matrix(5,5);
         for(int i=0;i<4;i++){
             if(i == 0){
                   Mytest.set(i,i,2);
             }
             Mytest.set(i,i,1);
             Mytest.set(i+1,i,1);
          }
        Mytest.print(9,6);
    }
    }