fft of numpy and octave different on transpose
Why NumPy and octave gave different results:
The inputs were different. The '
in octave is returning the complex conjugate transpose, not the transpose, .'
:
octave:6> [1+0.5j,3+0j,2+0j,8+3j]'ans = 1.0000 - 0.5000i 3.0000 - 0.0000i 2.0000 - 0.0000i 8.0000 - 3.0000i
So to make NumPy's result match octave's:
In [115]: np.fft.fft(np.array([1+0.5j, 3+0j, 2+0j, 8+3j]).conj()).reshape(-1, 1)Out[115]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])octave:7> fft([1+0.5j,3+0j,2+0j,8+3j]')ans = 14.0000 - 3.5000i 2.0000 + 4.5000i -8.0000 + 2.5000i -4.0000 - 5.5000i
In NumPy, the transpose of a 1D array is the same 1D array.That's why fft(np.array([1+0.5j, 3+0j, 2+0j, 8+3j]).transpose())
returns a 1D array.
Reshaping after taking the FFT of a 1D array:
You could take the FFT first, and then reshape. To make a 1D array 2-dimensional you could use reshape
to obtain a column-like array of shape (4,1), or use np.atleast_2d
followed by transpose
:
In [115]: np.fft.fft(np.array([1+0.5j, 3+0j, 2+0j, 8+3j]).conj()).reshape(-1, 1)Out[115]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])
or
In [116]: np.atleast_2d(np.fft.fft(np.array([1+0.5j, 3+0j, 2+0j, 8+3j]).conj())).TOut[116]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])
Taking the FFT of a 2D array:
np.fft.fft
takes the FFT over the last axis by default.This is why reshaping to shape (4, 1) did not work. Instead, reshape the array to (1, 4):
In [117]: np.fft.fft(np.reshape(np.array([1+0.5j,3+0j,2+0j,8+3j]), (1,4)).conj()).TOut[117]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])
Or you could use np.matrix
tomake a 2D matrix of shape (1, 4). Again the FFT is taken over the last axis, returns an array of shape (1, 4), which you can then transpose to get the desired result:
In [121]: np.fft.fft(np.matrix([1+0.5j, 3+0j, 2+0j, 8+3j]).conj()).TOut[121]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])
This, perhaps, gives you the neatest syntax. But be aware that this passes a np.matrix
as input but returns a np.ndarray
as output.
As Warren Weckesser pointed out, if you already have a 2D NumPy array, and wish to take the FFT of its columns, then you could pass axis=0
to the call to np.fft.fft.Also, The matrix
class (unlike the ndarray class) has a H
property which returns the complex conjugate transpose. Thus
In [114]: np.fft.fft(np.matrix([1+0.5j, 3+0j, 2+0j, 8+3j]).H, axis=0)Out[114]: array([[ 14.-3.5j], [ 2.+4.5j], [ -8.+2.5j], [ -4.-5.5j]])