简体   繁体   English

Python v / s MATLAB中的SVD命令

[英]SVD command in Python v/s MATLAB

I have m = 10, n = 5, A=randn(m,n);[U,S,V]=svd(A); 我有m = 10, n = 5, A=randn(m,n);[U,S,V]=svd(A); This returns a full 10x5 S matrix in MATLAB whereas Python only returns S as a 5x1 array. 这将在MATLAB中返回完整的10x5 S矩阵,而Python仅将S作为5x1数组返回。 How do I recover the complete S matrix in Python? 如何在Python中恢复完整的S矩阵? I have tried looking up several StackOverflow posts online but surprisingly doesn't shed light on this. 我尝试过在线查找一些StackOverflow帖子,但令人惊讶的是,这并没有阐明。

Also, how much does a Python IDE matter? 另外,Python IDE有多重要? I use Spyder but have been told that Vim is perhaps the most common. 我使用Spyder,但被告知Vim可能是最常见的。

Thanks a lot. 非常感谢。

The SVD of a matrix can be written as 矩阵的SVD可以写成

A = U S V^H

Where the ^H signifies the conjugate transpose . ^ H表示共轭转置 Matlab's svd command returns U, S and V, while numpy.linalg.svd returns U, the diagonal of S, and V^H. Matlab的svd命令返回U,S和V,而numpy.linalg.svd返回U,S的对角线和V ^ H。 Thus, to get the same S and V as in Matlab you need to reconstruct the S and also get the V: 因此,要获得与Matlab中相同的S和V,您需要重构S并获得V:

import numpy

m = 10
n = 5
A = numpy.random.randn(m, n)
U, sdiag, VH = numpy.linalg.svd(A)
S = numpy.zeros((m, n))
numpy.fill_diagonal(S, sdiag)
V = VH.T.conj()  # if you know you have real values only you can leave out the .conj()

To recover the Complete matrix you can do as follow : 要恢复完整矩阵,您可以执行以下操作:

import numpy as np
m = 10
n = 5
A=np.random.randn(m,n)
U,S,V =np.linalg.svd(A)

It's right that S.shape = (5,) . 正确的是S.shape = (5,)

You want something similar to https://www.mathworks.com/help/matlab/ref/svd.html with A = 4x2 where final S = 4×2 too. 您需要类似于https://www.mathworks.com/help/matlab/ref/svd.htmlA = 4x2 ,其中最终S = 4×2

To do that you define a matrix B = np.zeros(A.shape) . 为此,您定义一个矩阵B = np.zeros(A.shape) And you fill its diagonal with the element of S. By diagonal I mean where i==j as follow : 然后用S元素填充它的对角线。对角线是指i==j ,如下所示:

B = np.zeros(A.shape)
for i in range(m) :
    for j in range(n) :
        if i == j : B[i,j] = S[j]

Now B.shape = (10,5) as expected Or in a more compact form : 现在B.shape = (10,5)符合预期或更紧凑的形式:

C = np.array([[S[j] if i==j else 0 for j in range(n)] for i in range(m)])   

I hope it helps 希望对您有所帮助

For the second question, I use gedit (standard text editor) running the code in ipython shell. 对于第二个问题,我使用gedit(标准文本编辑器)在ipython shell中运行代码。

You can have a look to jupyter too 您也可以看看jupyter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM