将数学函数从 MATLAB 转换为 Python
Translating mathematical functions from MATLAB to Python
我目前正在进行一个项目,该项目涉及将在 MATLAB 中运行的程序翻译成 Python 以提高速度和效率。但是,我遇到了绊脚石。首先,我对波浪号 (~) 在 MATLAB 中表示什么以及如何在 python 中以相应的方式表示感到困惑。其次,我一直在搜索文档,我也很难在 MATLAB 中找到 'sign' 函数的等效函数。
indi = ~abs(indexd);
wav = (sum(sum(wv)))/(length(wv)*(length(wv)-1));
thetau = (sign(sign(wv - wav) - 0.1) + 1)/2;
thetad = (sign(sign(wav - wv) - 0.1) + 1)/2;
我已经将上一段代码中的 indexd 和 wv 转换为 numpy 数组。 Python替换 ~ 和符号函数的最有效的方法是什么?
如果您正在使用 numpy
,那么您还可以使用 ~
来反转事物,就像 MATLAB 一样。参见:What does the unary operator ~ do in numpy?. The sign
function also exists in numpy
. You use numpy.sign
。因此,上面的代码就是:
>>> import numpy as np
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(len(wv)*(len(wv)-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2
请注意,在矩阵上使用 MATLAB 中的 length
可以找到矩阵中的最大维度,而 numpy
使用 len
可以得到矩阵中的总行数。假设 wv
中的行数大于或等于 wv
中的列数,那么上面的代码将按您预期的那样工作。但是,如果您的列数多于行数,那么您需要找到最大的维度并使用它来代替...所以:
>>> import numpy as np
>>> maxdim = np.max(wv.shape)
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(maxdim*(maxdim-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2
上面对 numpy.sum
的调用实际上默认对所有维度求和,因此无需调用嵌套 sum
调用对整个矩阵求和(感谢 Divakar!)。
完全推荐你去这里看看很棒的 table 和从 MATLAB 翻译到 numpy
的指南:http://wiki.scipy.org/NumPy_for_Matlab_Users
我目前正在进行一个项目,该项目涉及将在 MATLAB 中运行的程序翻译成 Python 以提高速度和效率。但是,我遇到了绊脚石。首先,我对波浪号 (~) 在 MATLAB 中表示什么以及如何在 python 中以相应的方式表示感到困惑。其次,我一直在搜索文档,我也很难在 MATLAB 中找到 'sign' 函数的等效函数。
indi = ~abs(indexd);
wav = (sum(sum(wv)))/(length(wv)*(length(wv)-1));
thetau = (sign(sign(wv - wav) - 0.1) + 1)/2;
thetad = (sign(sign(wav - wv) - 0.1) + 1)/2;
我已经将上一段代码中的 indexd 和 wv 转换为 numpy 数组。 Python替换 ~ 和符号函数的最有效的方法是什么?
如果您正在使用 numpy
,那么您还可以使用 ~
来反转事物,就像 MATLAB 一样。参见:What does the unary operator ~ do in numpy?. The sign
function also exists in numpy
. You use numpy.sign
。因此,上面的代码就是:
>>> import numpy as np
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(len(wv)*(len(wv)-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2
请注意,在矩阵上使用 MATLAB 中的 length
可以找到矩阵中的最大维度,而 numpy
使用 len
可以得到矩阵中的总行数。假设 wv
中的行数大于或等于 wv
中的列数,那么上面的代码将按您预期的那样工作。但是,如果您的列数多于行数,那么您需要找到最大的维度并使用它来代替...所以:
>>> import numpy as np
>>> maxdim = np.max(wv.shape)
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(maxdim*(maxdim-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2
上面对 numpy.sum
的调用实际上默认对所有维度求和,因此无需调用嵌套 sum
调用对整个矩阵求和(感谢 Divakar!)。
完全推荐你去这里看看很棒的 table 和从 MATLAB 翻译到 numpy
的指南:http://wiki.scipy.org/NumPy_for_Matlab_Users