matlab中矩阵算子到python的转换

2024-04-16 18:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将以下Matlab代码转换为Python中的等效代码:

M.*((S*U)./max(realmin, M*(U'*U)))

其中:

S: n*n
M: n*m
U: n*m

我已经按照以下代码完成了:

x = (max(-sys.maxint, np.matmul(M, np.matmul(np.transpose(U), U))))
M = np.dot(M, ((np.matmul(S, U)) / x))

但我有以下错误:

x = (max(-sys.maxint, np.matmul(M, np.matmul(np.transpose(U), U))))
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

你能帮我怎么把Matlab代码转换成Python吗。你知道吗


Tags: the代码value错误npsysdotmax
1条回答
网友
1楼 · 发布于 2024-04-16 18:21:32

Matlab的max(a, b)是一个广播的元素最大操作。Python的max(a, b)不是。Python的max不理解数组,您不应该在数组上使用它。你知道吗

对于广播的elementwise最大值,需要^{}

numpy.maximum(whatever, whatever)

另外,Matlab的realminsmallest positive normalized double-precision floating-point number,而Python的sys.maxintlarge negative int(在python3上也不存在)。那可能不是你想要的。与Matlab的realmin等价的是

sys.float_info.min

或者

numpy.finfo(float).tiny

numpy.finfo(float).min是另一回事。)

相关问题 更多 >