1

As the title says, how can I find the null space of a matrix i.e. the nontrivial solution to the equation ax=0.

I've tried to use np.linalg.solve(a,b), which solves the equation ax=b. So setting b equal to an array of zeros with the same dimensions as matrix a, I only get the trivial solution i.e. x=0.

Turbotanten
  • 386
  • 3
  • 14
  • 1
    Did you see the question ["Python (NumPy, SciPy), finding the null space of a matrix"](https://stackoverflow.com/questions/5889142/python-numpy-scipy-finding-the-null-space-of-a-matrix)? – Warren Weckesser Apr 16 '18 at 08:42

2 Answers2

3

From SciPy Cookbook:

import numpy as np
from numpy.linalg import svd

def nullspace(A, atol=1e-13, rtol=0):
    A = np.atleast_2d(A)
    u, s, vh = svd(A)
    tol = max(atol, rtol * s[0])
    nnz = (s >= tol).sum()
    ns = vh[nnz:].conj().T
    return ns

Computes an approximate basis for the nullspace of A.

The algorithm used by this function is based on the singular value decomposition of A.

Parameters:

A : ndarray

A should be at most 2-D. A 1-D array with length k will be treated as a 2-D with shape (1, k)

atol : float

The absolute tolerance for a zero singular value. Singular values smaller than atol are considered to be zero.

rtol : float

The relative tolerance. Singular values less than rtol*smax are considered to be zero, where smax is the largest singular value.

If both atol and rtol are positive, the combined tolerance is the maximum of the two; that is:

tol = max(atol, rtol * smax)

Singular values smaller than tol are considered to be zero.

Return value:

ns : ndarray

If A is an array with shape (m, k), then ns will be an array with shape (k, n), where n is the estimated dimension of the nullspace of A. The columns of ns are a basis for the nullspace; each element in numpy.dot(A, ns) will be approximately zero.

fferri
  • 18,285
  • 5
  • 46
  • 95
0

you can diagonalize your matrix:

eigen_vects, eigen_vals = np.linalg.eig(a)

you then just have to pick the eigen vectors that correspond to 0 eigenvalues (possibly accounting for numerical precision).

Example:

np.linalg.eig(np.ones((3,3)))

(array([ -2.22044605e-16,   3.00000000e+00,   0.00000000e+00]),
 array([[-0.81649658,  0.57735027,  0.        ],
        [ 0.40824829,  0.57735027, -0.70710678],
        [ 0.40824829,  0.57735027,  0.70710678]]))

Here the 1st and 3rd vectors are your non trivial solutions.

Julien
  • 13,986
  • 5
  • 29
  • 53