python - What is numpy.fft.rfft and numpy.fft.irfft and its equivalent code in MATLAB -
i converting python code matlab , 1 of code uses numpy rfft. in documentation of numpy, says real input.
compute one-dimensional discrete fourier transform real input.
so did in matlab using abs results different.
python code
ffta = np.fft.rfft(a)
matlab code
ffta = abs(fft(a));
what have misunderstood?
the real fft in numpy uses fact fourier transform of real valued function "skew-symmetric", value @ frequency k
complex conjugate of value @ frequency n-k
k=1..n-1
(the correct term hermitian). therefore rfft
returns part of result corresponds nonpositive frequences.
for input of size n
rfft
function returns part of fft output corresponding frequences @ or below n/2
. therefore output of rfft
of size n/2+1
if n
(all frequences 0
n/2
), or (n+1)/2
if n
odd (all frequences 0 (n-1)/2
). observe function floor(n/2+1)
returns correct output size both , odd input sizes.
so reproduce rfft
in matlab
function rfft = rfft(a) ffta = fft(a); rfft = ffta(1:(floor(length(ffta)/2)+1)); end
for example
a = [1,1,1,1,-1,-1,-1,-1]; rffta = rfft(a)
would produce
rffta = columns 1 through 3: 0.00000 + 0.00000i 2.00000 - 4.82843i 0.00000 + 0.00000i columns 4 through 5: 2.00000 - 0.82843i 0.00000 + 0.00000i
now compare python
>>> np.fft.rfft(a) array([ 0.+0.j , 2.-4.82842712j, 0.-0.j , 2.-0.82842712j, 0.+0.j ])
reproducing irfft
to reproduce basic functionality of irfft
need recover missing frequences rfft
output. if desired output length even, output length can computed input length 2 (m - 1)
. otherwise should 2 (m - 1) + 1
.
the following code work.
function irfft = irfft(x,even=true) n = 0; % output length s = 0; % variable hold index of highest % frequency below n/2, s = floor((n+1)/2) if (even) n = 2 * (length(x) - 1 ); s = length(x) - 1; else n = 2 * (length(x) - 1 )+1; s = length(x); endif xn = zeros(1,n); xn(1:length(x)) = x; xn(length(x)+1:n) = conj(x(s:-1:2)); irfft = ifft(xn); end
now should have
>> irfft(rfft(a)) ans = 1.00000 1.00000 1.00000 1.00000 -1.00000 -1.00000 -1.00000 -1.00000
and also
abs( irfft(rfft(a)) - ) < 1e-15
for odd output length get
>> irfft(rfft(a(1:7)),even=false) ans = 1.0000 1.0000 1.0000 1.0000 -1.0000 -1.0000 -1.0000
Comments
Post a Comment