3

I'm trying to recreate a function from a discrete fourier transform. In Matlab it would be done like this:

function [y] = Fourier(dft,x)
n = length(dft);
y = cos(pi*(x+1)'*(0:n-1))*real(dft)+sin(pi*(x+1)'*(0:n-1))*imag(dft)
end

My attempt in Python is falling flat because I don't know how to add up all the coefficients correctly

def reconstruct(dft, x):
n = len(dft)
y = ([(coeff.real)*np.cos(np.pi*x*nn) + (coeff.imag)*np.cos(np.pi*x*nn) for coeff in dft for nn in range(0,n)])

But this isn't correct because I need to sum over n and add those sums together. Where am I off?

The equation I am trying to recreate is below:

Fourier Series

David Rinck
  • 6,637
  • 4
  • 45
  • 60

2 Answers2

5

You were running two nested loops instead of one. Try this:

y = ([(dft[nn].real)*np.cos(np.pi*x*nn) + (dft[nn].imag)*np.cos(np.pi*x*nn) for nn in range(0,n)])
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
5

You actually should not use a Python loop at all. You get more readable and much more efficient code if you vectorise the expression. Assuming dft is a complex-valued NumPy array, you could use

xn = x * np.arange(n)
y = dft.real * np.cos(xn) + dft.imag * np.sin(xn)

(Note that your Matlab code, your Python code and the formula you gave do three different things. The code I gave is closest to the Matlab code.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • I usually do that, but I ran into trouble because the function is a step function (not shown) with singularities. It gave me 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()' and dft.real won't work either... it's a list. – David Rinck May 01 '11 at 13:47