Filtering a sinusoidal wave with FFT - matlab

I am trying to write a code in Matlab which takes a one or sum of sinosudal waves imposed with noise and try to filter it using the following algo :
first i take the input and place it in a vector
then i apply fft() to that vector and abs() to that fft
- example if 'x' is the vector in which wave is stored then
- y= abs(fft(x))
now in 'y' i make all the elements less than a certain threshold value 0
then apply the ifft() function to get the filtered signal lets say 'x1'
but the final wave i get even though a sinusoidal wave it is out phase (see the graph).is it because iam applying abs() to the fft??
But the material which i got this algo from doesn't discuss about this.
Do i need to apply any other filter so that i get the actual wave??
here is the plot of the two waves: one i got from above procedure and the other the actual wave which is a sine wave with no noise:
my graph
see how my filtered wave and the actual wave are out of phase how to correct it ??
if you cannot understand the question or have anything you want to ask me please comment i will try to explain it.

You are assigning the absolute-values of the FFT result to y, hence you get REAL values. Doing ifft() on that simply assumes imaginary-parts are zero, hence the phase-shift.

Related

correct sampling points for FFT

I want to calculate the Fourier series of a signal using FFT on matlab. And I came across the following unexpected issue. Mere example
If I define a grid and then compute the fft as:
M=59;
x= deal(1*(0:M-1)/M);
y=3*cos(2*pi*x);
Yk=fftshift(fft2(y)/(M));
which gives me the exact analytic values expected: Yk(29)=1.5; Yk(31)=1.5; zeros anything else
but if I define the grid as, and repeat the fft calculation:
x=0:1/(M-1):1;
y=3*cos(2*pi*x);
Yk=fftshift(fft2(y)/(M));
got the Yk's values completely screwed up
This is an annoying issue since I have to analyse many signals data that was sampled as in the second method so the Yk's values will be wrong. Is there a way to workaround this? an option to tell something to the fft function about the way the signal was sampled. Have no way to resample the data in the correct way.
The main reason to avoid have spectral leaking, is that I do further operations with these Fourier terms individually Real and Imag parts. And the spectral leaking is messing the final results.
The second form of sampling includes one sample too many in the period of the cosine. This causes some spectral leaking, and adds a small shift to your signal (which leads to non-zero imaginary values). If you drop the last point, you'll cosine will again be sampled correctly, and you'll get rid of both of these effects. Your FFT will have one value less, I don't know if this will affect your analyses in any way.
x = 0:1/(M-1):1;
y = 3*cos(2*pi*x);
Yk = fftshift(fft2(y(1:end-1))/(M-1));
>> max(abs(imag(Yk)))
ans =
1.837610523517500e-16

Applying low pass filter

I want to simulate an interpolator in MATLAB using upsampling followed by a low pass filter. First I have up-sampled my signal by introducing 0's.
Now I want to apply a low pass filter in order to interpolate. I have designed the following filter:
The filter is exactly 1/8 of the normalized frequency because I need to downsample afterward. (it's a specific excersise to upsample interpolate and downsample in this particular order.)
However when I apply this filter to my data using the function filter(myfilter, data) the following signal is generated:
I really don't know what is happening to my signal because in theory I know an interpolated signal should appear. This is the first time I'm working in MATLAB with filters because till now we only had the theory and had to assume ideal filters and analytical solutions.
Can someone give me an indication what might be wrong? I use the following code:
clear all; close all;
% Settings parameters
fs=10e6;
N=10;
c=3/fs;
k=3;
M=8;
% Settings time and signal
t=0:fs^-1:N*fs^-1;
x=exp(-(t.^2)./(2.*c.^2)); % Gaussian signal
% Upsampling
tu=0:(fs*M)^-1:N*fs^-1;
xu=zeros(1,size(tu,2));
sample_range=1:M:size(xu,2);
for i=1:size(x,2);
xu(sample_range(i))=x(i);
end;
%% Direct Method
xf=filter(lpf5mhz,xu);
As suggested by hotpaw2's answer, the low-pass filter needs some time to ramp up to the input signal values. This is particularly obvious with signal with sharp steps such as yours (the signal implicitly includes a large step at the first sample since past samples are assumed to be zeros by the filter call). Also, with your design parameters the delay of the filter is greater than the maximum time range shown on your output plot (1e-6), and correspondingly the output remains very small for the time range shown.
To illustrate the point, we can take a look at the filtered output with smaller filter lengths (and correspondingly smaller delays), using filters generated with fir1(length,0.125):
Given a signal with a smoother transition such as a Gaussian pulse which has been sufficiently time delayed:
delay = 10/fs;
x=exp(-((t-delay).^2)./(2.*c.^2)); % Gaussian signal
the filter can better ramp up to the signal value:
The next thing you may noticed, is that the filtered output has 1/Mth the amplitude as the unfiltered signal. To get an interpolated signal with similar amplitude as the unfiltered signal you would have to scale the filter output with:
xf=M*filter(lpf5mhz,1,xu);
Finally, the signal is delayed by the filtering operation. So for comparison purposes you may want plot a time shifted version with:
filter_delay = (1/(M*fs))*(length(lpf5mhz)-1)/2;
plot(tu-(1/(M*fs))*(length(b)-1)/2, xf);
A low-pass filter only helps interpolate signals that are much longer than the length of the impulse response of the low-pass filter. Otherwise the output can be dominated by the filter transient.

how to use ifft function in MATLAB with experimental data

I am trying to use the ifft function in MATLAB on some experimental data, but I don't get the expected results.
I have frequency data of a logarithmic sine sweep excitation, therefore I know the amplitude [g's], the frequency [Hz] and the phase (which is 0 since the point is a piloting point).
I tried to feed it directly to the ifft function, but I get a complex number as a result (and I expected a real result since it is a time signal). I thought the problem could be that the signal is not symmetric, therefore I computed the symmetric part in this way (in a 'for' loop)
x(i) = conj(x(mod(N-i+1,N)+1))
and I added it at the end of the amplitude vector.
new_amp = [amplitude x];
In this way the new amplitude vector is symmetric, but now I also doubled the dimension of that vector and this means I have to double the dimension of the frequency vector also.
Anyway, I fed the new amplitude vector to the ifft but still I don't get the logarithmic sine sweep, although this time the output is real as expected.
To compute the time [s] for the plot I used the following formula:
t = 60*3.33*log10(f/f(1))/(sweep rate)
What am I doing wrong?
Thank you in advance
If you want to create identical time domain signal from specified frequency values you should take into account lots of details. It seems to me very complicated problem and I think it need very strength background on the mathematics behind it.
But I think you may work on some details to get more acceptable result:
1- Time vector should be equally spaced based on sampling from frequency steps and maximum.
t = 0:1/fs:N/fs;
where: *N* is the length of signal in frequency domain, and *fs* is twice the
highest frequency in frequency domain.
2- You should have some sort of logarithmic phases on the frequency bins I think.
3- Your signal in frequency domain must be even to have real signal in time domain.
I hope this could help, even for someone to improve it.

Matlab inverse fast fourier tansform for frequency-wavenumber field, do I need make conjugation and flip?

First I describe the physics, it is in a axisymmetric space, one sound source was placed at the original point, one sensor was placed on the axis under the source. Giving the source wave form, I try to get the sensor's waveform. all materiel parameter were known, for instance, sound speed, density.
I write the Matlab script to calculate it, by solving the sound propagation equation I can get
one function, say, A(w,k), w is frequency and k is wavenumber, this is so called frequency-wavenumber field. My matlab code like this,
discrete w and k, get a A array. first use FFT to k, get space and frequency information
then, FFT to w, get space and time information, that is the waveform at different point.
the fake code
for i_w=...
w=...
for i_k=...
k=...
M=A(w,k)
end
wave_space_freq=ifft(M)
end % here can specify the only point of the sensor
wave_space_freq=ifft(wave_space_freq)
My question is do I need to make conjugation and flip when I use IFFT,like ifft(M,0,fliplr(conj(M))) . because I saw some-others use them, but I don't understand why?
If you want a strictly real-valued result waveform (not complex with significant imaginary components), then the input to an IFFT has to be conjugate symmetric, such as:
ifft(dc_term,M,0,fliplr(conj(M))).

Complex FFT then Inverse FFT MATLAB

I am using the FFT function in Matlab in an attempt to analyze the output of a Travelling Wave Laser Model.
The of the model is in the time domain in the form (real, imaginary), with the idea being to apply the FFT to the complex output, to obtain phase and amplitude information in the frequency domain:
%load time_domain field data
data = load('fft_data.asc');
% Calc total energy in the time domain
N = size(data,1);
dt = data(2,1) - data (1,1);
field_td = complex (data(:,4), data(:,5));
wavelength = 1550e-9;
df = 1/N/dt;
frequency = (1:N)*df;
dl = wavelength^2/3e8/N/dt;
lambda = -(1:N)*dl +wavelength + N*dl/2;
%Calc FFT
FT = fft(field_td);
FT = fftshift(FT);
counter=1;
phase=angle(FT);
amptry=abs(FT);
unwraptry=unwrap(phase);
Following the unwrapping, a best fit was applied to the phase in the region of interest, and then subtracted from the phase itself in an attempt to remove wavelength dependence of phase in the region of interest.
for i=1:N % correct phase and produce new IFFT input
bestfit(i)=1.679*(10^10)*lambda(i)-26160;
correctedphase(i)=unwraptry(i)-bestfit(i);
ReverseFFTinput(i)= complex(amptry(i)*cos(correctedphase(i)),amptry(i)*sin(correctedphase(i)));
end
Having performed the best fit manually, I now have the Inverse FFT input as shown above.
pleasework=ifft(ReverseFFTinput);
from which I can now extract the phase and amplitude information in the time domain:
newphasetime=angle(pleasework);
newamplitude=abs(pleasework);
However, although the output for the phase is greatly different compared to the input in the time domain
the amplitude of the corrected data seems to have varied little (if at all!),
despite the scaling of the phase. Physically speaking this does not seem correct, as my understanding is that removing wavelength dependence of phase should 'compress' the pulsed input i.e shorten pulse width but heighten peak.
My main question is whether I have failed to use the inverse FFT correctly, or the forward FFT or both, or is this something like a windowing or normalization issue?
Sorry for the long winded question! And thanks in advance.
You're actually seeing two effects.
First the expected one goes. You're talking about "removing wavelength dependence of phase". If you did exactly that - zeroed out the phase completely - you would actually get a slightly compressed peak.
What you actually do is that you add a linear function to the phase. This does not compress anything; it is a well-known transformation that is equivalent to shifting the peaks in time domain. Just a textbook property of the Fourier transform.
Then goes the unintended one. You convert the spectrum obtained with fft with fftshift for better display. Thus before using ifft to convert it back you need to apply ifftshift first. As you don't, the spectrum is effectively shifted in frequency domain. This results in your time domain phase being added a linear function of time, so the difference between the adjacent points which used to be near zero is now about pi.