Search code examples
pythonnumpymatrix

Linearly independent columns of matrix in Python


I need to get a (mxn) matrix_A from input and:

  1. Find m linearly independent columns of it and put them into another matrix_B;
  2. Put the remaining columns of matrix_A into a matrix_N;
  3. And also I need to know the index of those columns I put in matrix_B and matrix_N so I can access them later to change the columns (the indexes can be in an array as long as I can use that to find the columns in the original matrix_A).

Example:

If I have:

matriz_A = [[-3. 1.  4. 0. 0.], 
            [ 1. 0. -1. 1. 0.], 
            [ 1. 0.  1. 0. 1.]]

I need matrix_B to be like:

matrix_B = [[1. 0. 0.], 
            [0. 1. 0.], 
            [0. 0. 1.]]

and matrix_N to be:

matrix_N = [[-3.  4.], 
            [ 1. -1.], 
            [ 1.  1.]]

And also I need to know that indexes of matrix_B are [1, 3, 4] and indexes of matrix_N are [0, 2].

How can I make that in Python? I'm using numpy to get the matrix_A from input as a matrix of floats.


Solution

  • I think the easiest way to find the vectors is to use sympy. It allows to find the index of the first linearly independant vectors. In your case, the first linearly independant are the 3 first columns.

    import sympy
    import numpy as np
    
    matrix_a = np.array([[-3, 1, 4, 0, 0], [1, 0, -1, 1, 0], [1, 0, 1, 0, 1]])
    echelon, index = sympy.Matrix(matrix_a).rref()
    

    The index variable is a tuple of the linearly independant columns. Let's check that index is (0, 1, 2)

    >>> index
    (0, 1, 2)
    

    To finish, we have to define matrix_b and matrix_n:

    matrix_b = matrix_a[:, index]
    n_index =  np.setxor1d(np.arange(matrix_a.shape[1]), index)
    matrix_n = matrix_a[:, n_index]
    

    Finally let's verify:

    >>> matrix_b
    array([[-3,  1,  4],
           [ 1,  0, -1],
           [ 1,  0,  1]])
    
    >>> matrix_n
    array([[0, 0],
           [1, 0],
           [0, 1]])