Example: QR Factorization of a Matrix

The QR Factorization of a Matrix is performed. A linear system is then solved using the factorization. The rank of the input matrix is also computed.
import com.imsl.math.*;

public class QREx1 {
    public static void main(String args[]) throws SingularMatrixException {
        double	a[][] = {
            {1, 2,  4},
            {1, 4, 16},
            {1, 6, 36},
            {1, 8, 64}
        };
        double	b[]	  = {4.999, 9.001, 12.999, 17.001};
        
        // Compute the QR factorization of A
        QR	qr = new QR(a);
        
        // Solve Ax = b
        double	x[] = qr.solve(b);
        new PrintMatrix("x").print(x);
        
        // Print Q and R.
        new PrintMatrix("Q").print(qr.getQ());
        new PrintMatrix("R").print(qr.getR());
        
        // Find the rank of A.
        int rank = qr.getRank();
        System.out.println("rank = "+rank);
    }
}

Output

     x
     0     
0   0.999  
1   2      
2  -0      

                 Q
     0       1       2       3     
0  -0.053  -0.542   0.808  -0.224  
1  -0.213  -0.657  -0.269   0.671  
2  -0.478  -0.346  -0.449  -0.671  
3  -0.85    0.393   0.269   0.224  

             R
     0        1       2     
0  -75.26  -10.63   -1.594  
1    0      -2.647  -1.153  
2    0       0       0.359  
3    0       0       0      

rank = 3
Link to Java source.