将自定义离散傅里叶变换从MATLAB转换为Python的问题

将自定义离散傅里叶变换从MATLAB转换为Python的问题,python,matlab,numpy,dft,Python,Matlab,Numpy,Dft,我正在为某人开发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**

我正在为某人开发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处理计算的方式略有不同,但我不知道为什么或如何解决这个问题。

Numpy数组使用
*
进行元素相乘

对于使用numpy数组的矩阵乘法,需要
np.dot(w1,w2)
(不适用于numpy矩阵)

确保你清楚地看到了屏幕。有一个很好的帮助页面“Matlab用户的Numpy”:

目前似乎不起作用,所以


另外,使用
t.t
转置一个名为
t
的numpy数组-

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绘图-

Numpy图-


在你的matlab代码中,你有一个
f*t'
,我假设它的意思是t转置。将你的
w1
计算为你目前拥有的东西的总和,看看这是否有效不,等等。不可能。@chw21是对的,这是介于
f
和转置的
t
之间的kronecker产品。Python是否可能在那里进行元素相乘?是的,将两个numpy数组相乘会返回一个数组,每个元素都是两个对应元素的乘积。这些输入是numpy数组还是矩阵?关于numpy数组和矩阵之间的差异: