我正在为某人开发Python软件,他们特别要求我在我的程序中使用他们用MATLAB编写的DFT函数。我的翻译显然不起作用,用sin(2 * pi * r)测试。 下面的MATLAB函数:
function X=dft(t,x,f)
% Compute DFT (Discrete Fourier Transform) at frequencies given
% in f, given samples x taken at times t:
% X(f) = sum { x(k) * e**(2*pi*j*t(k)*f) }
% k
shape = size(f);
t = t(:); % Format 't' into a column vector
x = x(:); % Format 'x' into a column vector
f = f(:); % Format 'f' into a column vector
W = exp(-2*pi*j * f*t');
X = W * x;
X = reshape(X,shape);
我的Python解释:
def dft(t, x, f):
i = 1j #might not have to set it to a variable but better safe than sorry!
w1 = f * t
w2 = -2 * math.pi * i
W = exp(w1 * w2)
newArr = W * x
return newArr
为什么我遇到问题? MATLAB代码工作正常,但Python转换输出一个奇怪的增加正弦曲线而不是傅里叶变换。我觉得Python处理计算的方式略有不同,但我不知道为什么或如何解决这个问题。
答案 0 :(得分:1)
Numpy数组与*
进行元素相乘。
使用numpy数组进行矩阵乘法需要np.dot(w1,w2)
(不是numpy矩阵的情况)
确保您清楚distinction between Numpy arrays and matrices。有一个很好的帮助页面“Numpy for Matlab Users”:
http://wiki.scipy.org/NumPy_for_Matlab_Users
目前似乎没有工作here is a temporary link。
另外,使用t.T
转置名为t
的numpy数组。
答案 1 :(得分:1)
这是您的MATLAB代码 -
t = 0:0.005:10-0.005;
x = sin(2*pi*t);
f = 30*(rand(size(t))+0.225);
shape = size(f);
t = t(:); % Format 't' into a column vector
x = x(:); % Format 'x' into a column vector
f = f(:); % Format 'f' into a column vector
W = exp(-2*pi*1j * f*t'); %//'
X = W * x;
X = reshape(X,shape);
figure,plot(f,X,'ro')
这里有一个numpy移植代码的版本可能看起来像 -
import numpy as np
from numpy import math
import matplotlib.pyplot as plt
t = np.arange(0, 10, 0.005)
x = np.sin(2*np.pi*t)
f = 30*(np.random.rand(t.size)+0.225)
N = t.size
i = 1j
W = np.exp((-2 * math.pi * i)*np.dot(f.reshape(N,1),t.reshape(1,N)))
X = np.dot(W,x.reshape(N,1))
out = X.reshape(f.shape).T
plt.plot(f, out, 'ro')
MATLAB Plot -
Numpy Plot -