1

Take in two 3 dimensional vectors, each represented as an array, and tell whether they are linearly independent. I tried to use np.linalg.solve() to get the solution of x, and tried to find whether x is trivial or nontrivial. But it shows 'LinAlgError: Last 2 dimensions of the array must be square'. Can anyone help me how to figure that out?

from sympy import *
import numpy as np
from scipy import linalg
from numpy import linalg

v1 = np.array([0, 5, 0])
v2 = np.array([0, -10, 0])
a = np.array([v1,v2])
b = np.zeros(3)
x = np.linalg.solve(a, b)
RRR
  • 63
  • 2
  • 8
  • 2
    Show what you tried as properly formatted code in the question. – Michael Butscher Oct 07 '20 at 05:56
  • Do you know how to do it by hand? Is this really a programming question, or is it a math question? – Karl Knechtel Oct 07 '20 at 06:07
  • Does this answer your question? [How to find linearly independent rows from a matrix](https://stackoverflow.com/questions/28816627/how-to-find-linearly-independent-rows-from-a-matrix) – Qiu Feb 16 '23 at 12:53

2 Answers2

2

As your final matrix will be in a rectangular form, a simple approach of EigenValues will not work. You need to use the library of sympy

import sympy 
import numpy as np
matrix = np.array([
  [0, 5, 0],
  [0, -10, 0]
])

_, indexes = sympy.Matrix(matrix).T.rref()  # T is for transpose
print(indexes)

This will print the indexes of linearly independent rows. To further print them from the matrix, use

print(matrix[indexes,:])

To answer your specific question, check if two vectors are linearly dependant or not. You can most definitely use an if statement afterwards if it is the two vectors you are always going to check.

if len(indexes) == 2:
    print("linearly independant")
else:
    print("linearly dependant")
0

If one eigenvalue of the matrix is zero, its corresponding eigenvector is linearly dependent.

So the following code would work for simple case:

from sympy import *
import numpy as np
from scipy import linalg
from numpy import linalg

matrix = np.array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 1, 0], [1, 0, 0,
                  1]])

(lambdas, V) = np.linalg.eig(matrix.T)
print matrix[lambdas == 0, :]

Output: [[0 1 1 0]]

  • I tried it already, but it shows 'LinAlgError: Last 2 dimensions of the array must be square'. – RRR Oct 07 '20 at 06:16