10

There must be a simple way to get a null space of a small (say 3x3) matrix in python's numpy or scipy.

MATLAB can be good about this. Let's say:

A = [1 2 3; 
     2 3 4; 
     2 4 6]

rank(A) % rank is 2 
null(A, 'r') % ask matlab to be ('r') reasonable about 
             % its choice of a vector in A's nullspace

and the output of the last command is:

 1 
-2 
 1

It appears - and is this true? - that things arn't quite as simple in numpy:

import numpy as np
A = array(([1, 2, 3], [2, 3, 4], [2, 4, 6])) 
np.linalg.matrix_rank(A) # ok, getting the rank of a matrix is this esay, even if
                         # it takes more keystrokes, but how about its null space

From what I've searched so far, it appears that one needs to call the svd decomposition function first to get the nullspace.

There must be a simpler way to do this in python.

Also, in matlab one could say:

format rat

to avoid stairing at long decimal fractions in output matrices. (e.g. when the format is set to 'rational' an entry in an output matrix would look like 1/2 instead of the uglier looking 0.5000000)

Does python have a similar feature, or is anyone using python doomed to look at these decimals forever?

Thanks in advance.

d.

4

1 回答 1

14

从 null.m 的 matlab 代码中可以看出,它们还调用 svd 来获取空空间。事实上,他们也调用 svd 来获得排名(我没有在这里复制,但请随意阅读大约 4 行的代码)。

function Z = null(A,how)
   % clip
   [~,S,V] = svd(A,0);
   if m > 1, s = diag(S);
      elseif m == 1, s = S(1);
      else s = 0;
   end
   tol = max(m,n) * max(s) * eps(class(A));
   r = sum(s > tol);
   Z = V(:,r+1:n);
end

这是一个python版本,这个函数将计算方阵的秩和零空间。它返回秩和 (N, N - R) 数组,其中 N 是矩阵的大小,R 是秩。

import numpy as np

def null(a, rtol=1e-5):
    u, s, v = np.linalg.svd(a)
    rank = (s > rtol*s[0]).sum()
    return rank, v[rank:].T.copy()
于 2013-11-06T19:43:04.237 回答