dav*_*ave 9 python matlab numpy matrix linear-algebra
必须有一种简单的方法来获得python的numpy或scipy中的小(例如3x3)矩阵的零空间.
MATLAB可以很好地解决这个问题.让我们说:
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
Run Code Online (Sandbox Code Playgroud)
并且最后一个命令的输出是:
1
-2
1
Run Code Online (Sandbox Code Playgroud)
它似乎 - 这是真的吗? - 在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
Run Code Online (Sandbox Code Playgroud)
从我到目前为止搜索到的内容来看,似乎需要首先调用
svd分解函数来获取nullspace.
在python中必须有一种更简单的方法.
另外,在matlab中可以说:
format rat
Run Code Online (Sandbox Code Playgroud)
避免在输出矩阵中以小的小数位数进行爬行.(例如,当格式设置为'rational'时,输出矩阵中的条目看起来像1/2而不是看起来更丑陋0.5000000)
python是否有类似的功能,或者是否有人使用python注定要永远查看这些小数?
提前致谢.
d.
Bi *_*ico 12
正如你从matlab代码中看到的null.m,他们也调用svd来获取null空间.事实上,他们也调用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
Run Code Online (Sandbox Code Playgroud)
这是一个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()
Run Code Online (Sandbox Code Playgroud)