gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:11 25 4
gpt4 key购买 nike

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

最佳答案

这是您的 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

关于python - 将自定义离散傅立叶变换从 MATLAB 转换为 Python 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29607116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com