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

4

我正在为某人开发Python软件,他们特别要求我在我的程序中使用他们编写的DFT函数,该函数是用MATLAB编写的。我的转换根本不起作用,使用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在处理计算上有些微不同,但我不知道如何解决这个问题。


1
在你的Matlab代码中,你有一个 f*t',我认为这意味着t转置。将你此刻拥有的东西相加计算出 w1,看看是否有效。--不,等等。那不可能是这样的。 - chw21
是的,将两个numpy数组相乘会返回一个数组,其中每个元素都是两个对应元素的乘积。 - chw21
关于numpy数组和矩阵的区别:https://dev59.com/N2855IYBdhLWcg3wxHcq#15406440 - Lee
@Divakar,这个函数对你有用吗?我已经用np.dot()替换了所有的乘法,并进行了t.T操作,但现在我得到的只是原始的正弦曲线(至少在绘图时是这样)。 - Trilbador
f 是1d还是2d?在MATLAB中,所有的东西都是2d或更高维度,在numpy中数组可以是1d。对于1d数组进行转置不会有任何变化。 - hpaulj
显示剩余7条评论
2个回答

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

enter image description here

Numpy 绘图 -

enter image description here


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接