Computing the Rank

In [16]:
#keep
import numpy as np
In [17]:
#keep
n = 5
A = np.random.randn(n, n)

Now decrease the rank of A:

In [18]:
#keep
A[4] = A[0] + 5 * A[2]
A[1] = 3 * A[0] -2 * A[2]

What should the rank be now?


Let's run Gaussian Elimination:

In [19]:
#keep
np.set_printoptions(precision=4)

for i in range(n):
    # find biggest entry
    j = max(
        (j for j in range(i, n)),
        key=lambda j: abs(A[j, i]))
    
    # swap rows i and piv_row
    row_i = A[i].copy()
    row_j = A[j]
    A[i] = row_j
    A[j] = row_i
    
    # eliminate down
    for j in range(i+1, n):
        A[j] -= A[i] * A[j,i]/A[i,i]
        
    print(A)
    print()
[[  6.2344e+00  -5.5712e+00  -2.7390e-01  -1.1447e+00  -4.1407e+00]
 [  0.0000e+00   4.5908e+00  -3.3457e+00   2.1521e+00   5.3686e-01]
 [ -2.2204e-16  -2.7005e-01   1.9681e-01  -1.2660e-01  -3.1580e-02]
 [  0.0000e+00  -1.5893e+00  -1.1484e+00   9.0711e-01  -1.9974e+00]
 [  0.0000e+00   1.3502e+00  -9.8403e-01   6.3298e-01   1.5790e-01]]

[[  6.2344e+00  -5.5712e+00  -2.7390e-01  -1.1447e+00  -4.1407e+00]
 [  0.0000e+00   4.5908e+00  -3.3457e+00   2.1521e+00   5.3686e-01]
 [ -2.2204e-16   0.0000e+00  -2.7756e-17  -2.7756e-17   1.0408e-16]
 [  0.0000e+00   0.0000e+00  -2.3067e+00   1.6522e+00  -1.8116e+00]
 [  0.0000e+00   0.0000e+00   2.2204e-16   0.0000e+00   5.5511e-17]]

[[  6.2344e+00  -5.5712e+00  -2.7390e-01  -1.1447e+00  -4.1407e+00]
 [  0.0000e+00   4.5908e+00  -3.3457e+00   2.1521e+00   5.3686e-01]
 [  0.0000e+00   0.0000e+00  -2.3067e+00   1.6522e+00  -1.8116e+00]
 [ -2.2204e-16   0.0000e+00   0.0000e+00  -4.7635e-17   1.2588e-16]
 [  0.0000e+00   0.0000e+00   0.0000e+00   1.5904e-16  -1.1887e-16]]

[[  6.2344e+00  -5.5712e+00  -2.7390e-01  -1.1447e+00  -4.1407e+00]
 [  0.0000e+00   4.5908e+00  -3.3457e+00   2.1521e+00   5.3686e-01]
 [  0.0000e+00   0.0000e+00  -2.3067e+00   1.6522e+00  -1.8116e+00]
 [  0.0000e+00   0.0000e+00   0.0000e+00   1.5904e-16  -1.1887e-16]
 [ -2.2204e-16   0.0000e+00   0.0000e+00   6.1630e-33   9.0277e-17]]

[[  6.2344e+00  -5.5712e+00  -2.7390e-01  -1.1447e+00  -4.1407e+00]
 [  0.0000e+00   4.5908e+00  -3.3457e+00   2.1521e+00   5.3686e-01]
 [  0.0000e+00   0.0000e+00  -2.3067e+00   1.6522e+00  -1.8116e+00]
 [  0.0000e+00   0.0000e+00   0.0000e+00   1.5904e-16  -1.1887e-16]
 [ -2.2204e-16   0.0000e+00   0.0000e+00   6.1630e-33   9.0277e-17]]

Now what is the rank of that matrix?