FFT, but with a linear wavelength scale - matlab

When the FFT is performed on a function of time u in Matlab, a complex spectrum uf is returned. To plot the spectral amplitude abs(uf) against its frequency content, a frequency grid can be made to accommodate uf. I can associate a wavelength grid with the frequency grid, and plot uf against that also. The spacing between each element in the frequency array is constant, but since wavelength ~ 1/frequency, the spacing between each point in the wavelength array varies over the array index. I am curious if there is a way to take the FFT of a function of time to yield a spectrum in wavelength that has constant spacing. Here is my code in Matlab:
clc;
close all;
clear all;
lam = 800e-9; % Wavelength (m)
c = 3e8; % Light speed (m/s)
nt = 8192; % Temporal grid resolution
T = 400*1e-15; % Temporal grid size (s)
dt = T/nt; % Temporal pixel spacing
df = 1/(nt*dt); % Frequency pixel spacing
ff = [(0:nt/2-1) (-nt/2:-1)]*df; % Frequency grid
ff = fftshift(ff);
wav = c./ff; % Wavelength array (spacing is not constant between each element)
for k = 1:nt
tt(k) = (-nt/2+k-1)*dt; % Time array
u(k) = cos(2*pi*c/lam*tt(k)); % Function of time
end
%Now I can take FFT:
uf = fftshift(fft(u)); % The spectrum of my function. The FFT has yielded a spectrum associated with a frequency array of linearly spaced elements (ff).
Both plots of spectral amplitude vs. wavelength and vs. frequency yield good results.
figure(1)
plot(ff,abs(uf))
title('Spectral amplitude vs frequency')
xlabel('Frequency (Hz)')
ylabel('Spectral amplitude')
figure(2)
plot(wav,abs(uf))
title('Spectral amplitude vs wavelength')
xlabel('Wavelength (m)')
ylabel('Spectral amplitude');
But my wavelength array does not have constant spacing:
figure(3)
plot(ff)
title('Frequency array')
ylabel('Frequency (Hz)')
xlabel('Index')
figure(4)
plot(wav)
xlim([(nt/2 +1) (nt/2 + 100)])
title('Wavelength array')
ylabel('Wavelength (m)')
xlabel('Index')

You should make a linearly spaced wavelength array and interpolate your data to find the linearly spaced y values.

Related

Fourier transform and FFT for an arbitrary plot using MATLAB

I have a simple problem but since I have not used MATLAB Fourier Transform tools I need some help. I have a plot obtained from n excel file. The plot is in time domain. Time range for the plot is 0 to 50 ps. And I have data for the y component of the plot every 0.5 fs. Basically the plot contains 100000 data printed every 0.5fs. Now I want to get the Fourier transform of this plot. What should i do? The following is a simple format for my excel file that includes the data I needed to have the time-domain plot.
0 116.0080214
0.0005 116.051128
0.001 116.0939229
0.0015 116.1362197
0.002 116.1776665
0.0025 116.2178118
0.003 116.256182
.
.
.
.
50.0 123.000
The first column is time in ps. Thank you so much in advance for you helps. Best, HRJ
I have adapted this page for the solution.
Fs = 100000/50; % Sampling frequency (in 1/ps)
T = 1/Fs; % Sample time (in ps)
L = 100000; % Length of signal
t = (0:L-1)*T; % Time vector; your first column should replace this
% Sum of a 50 1/ps sinusoid and a 120 1/ps sinusoid
% Your second column would replace y
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
y = x + 2*randn(size(t)); % Sinusoids plus noise
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
close all
subplot(2,1,1)
% Plot your original signal
plot(Fs*t(1:100),y(1:100))
title('Signal Corrupted with Noise')
xlabel('time (fs)')
% Plot single-sided amplitude spectrum.
subplot(2,1,2)
plot(f,2*abs(Y(1:NFFT/2+1)))
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (1/ps)')
ylabel('|Y(f)|')

Frequency spectrum of signal in Matlab

Here is the code I use to plot a function in frequency domain in Matlab:
dt = 1/10000; % sampling rate
et = 0.1; % end of the interval
t = 0:dt:et; % sampling range
y = 2+sin(2.*pi.*50.*t)+18.*sin(2.*pi.*90.*t)+6.*sin(2.*pi.*180.*t); % sample the signal
subplot(2,1,1); % first of two plots
plot(t,y); grid on % plot with grid
xlabel('Time (s)'); % time expressed in seconds
ylabel('Amplitude'); % amplitude as function of time
Y = fft(y); % compute Fourier transform
n = size(y,2)/2; % 2nd half are complex conjugates
amp_spec = abs(Y)/n; % absolute value and normalize
subplot(2,1,2); % second of two plots
freq = (0:100)/(2*n*dt); % abscissa viewing window
stem(freq,amp_spec(1:101)); grid on % plot amplitude spectrum
xlabel('Frequency (Hz)'); % 1 Herz = number of cycles/second
ylabel('Amplitude'); % amplitude as function of frequency
The problem is, when I zoom in my graph I don't see peaks exactly on 50Hz, 90Hz and 180Hz.
What did I do wrong in my code?
The problem is that in order to get perfect spectra (peaks on 50,90,180 and 0 otherwise), your interval should be a multiplier of all the frequencies.
Explanation: consider y=sin(2.*pi.*t). Use your code to plot it with:
1) et = 1-dt;
2) et = 1;
In the first case, if you zoom in, you will see that peak is perfectly on 1 Hz. In the second case it is not (also very close).
Why? Because you are working with the finite number of points, and, consequently, finite number of frequencies. If 1 Hz is among this set of frequencies (1st case), you will get perfect peak at 1 Hz at zeros at all others frequencies.
In case 2 there is no 1 Hz frequency in your set, so you will get peak on the nearest frequencies (and also it will have finite width).
Ultimately, in your original code, there are no 50, 90, 180 Hz frequencies in your full set of frequencies.

on the use and understanding of pwelch in matlab

I'm using the pwelch method in matlab to compute the power spectra for some wind speed measurements. So, far I have written the following code as an example:
t = 10800; % number of seconds in 3 hours
t = 1:t; % generate time vector
fs = 1; % sampling frequency (seconds)
A = 2; % amplitude
P = 1000; % period (seconds), the time it takes for the signal to repeat itself
f1 = 1/P; % number of cycles per second (i.e. how often the signal repeats itself every second).
y = A*sin(2*pi*f1*t); % signal
fh = figure(1);
set(fh,'color','white','Units', 'Inches', 'Position', [0,0,6,6],...
'PaperUnits', 'Inches', 'PaperSize', [6,6]);
[pxx, f] = pwelch(y,[],[],[],fs);
loglog(f,10*(pxx),'k','linewidth',1.2);
xlabel('log10(cycles per s)');
ylabel('Spectral Density (dB Hz^{-1})');
I cannot include the plot as I do not have enough reputation points
Does this make sense? I'm struggling with the idea of having noise at the right side of the plot. The signal which was decomposed was a sine wave with no noise, where does this noise come from? Does the fact that the values on the yaxis are negative suggest that those frequencies are negligible? Also, what would be the best way to write the units on the y axis if the wind speed is measured in m/s, can this be converted to something more meaningful for environmental scientists?
Your results are fine. dB can be confusing.
A linear plot will get a good view,
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
y = sin(2 * pi * 50 * t); % 50Hz signal
An fft approach,
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
subplot(1,2,1);
plot(f,2*abs(Y(1:NFFT/2+1)))
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
pwelch approach,
subplot(1,2,2);
[pxx, freq] = pwelch(y,[],[],[],Fs);
plot(freq,10*(pxx),'k','linewidth',1.2);
xlabel('Frequency (Hz)');
ylabel('Spectral Density (Hz^{-1})');
As you can see they both have peak at 50Hz.
Using loglog for both,
So "noise" is of 1e-6 and exists in fft as well, and can be ignored.
For your second question, I don't think the axis will change it will be frequency again. For Fs you should use the sampling frequency of wind speed, like if you have 10 samples of speed in one second your Fs is 10. Higher frequencies in your graph means more changes in wind speed and lower frequencies represent less changes for the speed.

Fourier transform and LTI filter and frequency response in Matlab

I'm new to Matlab for LTI signal processing and wondering if anyone can help with something that I'm sure is meant to be basic. I've spent hours and hours researching and obtaining background information and still cannot obtain a clear path to tackle these problems. So far, from scratch, I have generated a signal required and managed to use the fft function to produce the signal's DFT:
function x = fourier_rikki(A,t,O)
Fs = 1000;
t = 0:(1/Fs):1;
A = [0.5,0,0.5];
N = (length(A) - 1)/2;
x = zeros(size(t));
f1 = 85;
O1 = 2*pi*f1;
for k = 1:length(A)
x1 = x + A(k)*exp(1i*O1*t*(k-N-1));
end
f2 = 150;
O2 = 2*pi*f2;
for k = 1:length(A);
x2 = x + A(k)*exp(1i*O2*t*(k-N-1));
end
f3 = 330;
O3 = 2*pi*f3;
for k = 1:length(A);
x3 = x + A(k)*exp(1i*O3*t*(k-N-1));
end
signal = x1 + x2 + x3;
figure(1);
subplot(3,1,1);
plot(t, signal);
title('Signal x(t) in the Time Domain');
xlabel('Time (Seconds)');
ylabel('x(t)');
X = fft(signal); %DFT of the signal
subplot(3,1,2);
plot(t, X);
title('Power Spectrum of Discrete Fourier Transform of x(t)');
xlabel('Time (Seconds)');
ylabel('Power');
f = linspace(0, 1000, length(X)); %?
subplot(3,1,3);
plot(f, abs(X)); %Only want the positive values
title('Spectral Frequency');
xlabel('Frequency (Hz)'); ylabel('Power');
end
At this stage, I'm assuming this is correct for:
"Generate a signal with frequencies 85,150,330Hz using a sampling frequency of 1000Hz - plot 1seconds worth of the signal and its Discrete Fourier Transform."
The next step is to "Find the frequency response of an LTI system that filters out the higher and lower frequencies using the Fourier Transform". I'm stuck trying to create an LTI system that does that! I have to be left with the 150Hz signal, and I'm guessing I perform the filtering on the FFT, perhaps using conv.
My course is not a programming course - we are not assessed on our programming skills and I have minimal Matlab experience - basically we have been left to our own devices to struggle through, so any help would be greatly appreciated! I am sifting through tonnes of different examples and searching Matlab functions using 'help' etc, but since each one is different and does not have a break down of the variables used, explaining why certain parameters/values are chosen etc. it is just adding to the confusion.
Among many (many) others I have looked at:
http://www.ee.columbia.edu/~ronw/adst-spring2010/lectures/matlab/lecture1.html
http://gribblelab.org/scicomp/09_Signals_and_sampling.html section 10.4 especially.
As well as Matlab Geeks examples and Mathworks Matlab function explanations.
I guess the worst that can happen is that nobody answers and I continue burning my eyeballs out until I manage to come up with something :) Thanks in advance.
I found this bandpass filter code as a Mathworks example, which is exactly what needs to be applied to my fft signal, but I don't understand the attenuation values Ast or the amount of ripple Ap.
n = 0:159;
x = cos(pi/8*n)+cos(pi/2*n)+sin(3*pi/4*n);
d = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',1/4,3/8,5/8,6/8,60,1,60);
Hd = design(d,'equiripple');
y = filter(Hd,x);
freq = 0:(2*pi)/length(x):pi;
xdft = fft(x);
ydft = fft(y);
plot(freq,abs(xdft(1:length(x)/2+1)));
hold on;
plot(freq,abs(ydft(1:length(x)/2+1)),'r','linewidth',2);
legend('Original Signal','Bandpass Signal');
Here is something you can use as a reference. I think I got the gist of what you were trying to do. Let me know if you have any questions.
clear all
close all
Fs = 1000;
t = 0:(1/Fs):1;
N = length(t);
% 85, 150, and 330 Hz converted to radian frequency
w1 = 2*pi*85;
w2 = 2*pi*150;
w3 = 2*pi*330;
% amplitudes
a1 = 1;
a2 = 1.5;
a3 = .75;
% construct time-domain signals
x1 = a1*cos(w1*t);
x2 = a2*cos(w2*t);
x3 = a3*cos(w3*t);
% superposition of 85, 150, and 330 Hz component signals
x = x1 + x2 + x3;
figure
plot(t(1:100), x(1:100));
title('unfiltered time-domain signal, amplitude vs. time');
ylabel('amplitude');
xlabel('time (seconds)');
% compute discrete Fourier transform of time-domain signal
X = fft(x);
Xmag = 20*log10(abs(X)); % magnitude spectrum
Xphase = 180*unwrap(angle(X))./pi; % phase spectrum (degrees)
w = 2*pi*(0:N-1)./N; % normalized radian frequency
f = w./(2*pi)*Fs; % radian frequency to Hz
k = 1:N; % bin indices
% plot magnitude spectrum
figure
plot(f, Xmag)
title('frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% frequency vector of the filter. attenuates undesired frequency components
% and keeps desired components.
H = 1e-3*ones(1, length(k));
H(97:223) = 1;
H((end-223):(end-97)) = 1;
% plot magnitude spectrum of signal and filter
figure
plot(k, Xmag)
hold on
plot(k, 20*log10(H), 'r')
title('frequency-domain signal (blue) and filter (red), magnitude vs. bin index');
xlabel('bin index');
ylabel('magnitude (dB)');
% filtering in frequency domain is just multiplication
Y = X.*H;
% plot magnitude spectrum of filtered signal
figure
plot(f, 20*log10(abs(Y)))
title('filtered frequency-domain signal, magnitude vs. frequency');
xlabel('frequency (Hz)');
ylabel('magnitude (dB)');
% use inverse discrete Fourier transform to obtain the filtered time-domain
% signal. This signal is complex due to imperfect symmetry in the
% frequency-domain, however the imaginary components are nearly zero.
y = ifft(Y);
% plot overlay of filtered signal and desired signal
figure
plot(t(1:100), x(1:100), 'r')
hold on
plot(t(1:100), x2(1:100), 'linewidth', 2)
plot(t(1:100), real(y(1:100)), 'g')
title('input signal (red), desired signal (blue), signal extracted via filtering (green)');
ylabel('amplitude');
xlabel('time (seconds)');
Here is the end result...

how can i fourier transform with negative frequency uncut in matlab?

clear all;
Fs=100; %sampling rate
t=-10:(1/Fs):10;
for i=1:20*Fs+1
if -10<t(i) && t(i)<-9
x(i)= -1;
elseif -9<t(i) && t(i)<-8
x(i)=1;
elseif i>2*Fs+1
x(i)=x(i-(2*Fs));
shown above is the code for rectangular function with its domain [-10 10] and period of 2
and here is my positiveFFT function
function [X,freq]=positiveFFT(x,Fs)
N=length(x); %get the number of points
k=0:N-1; %create a vector from 0 to N-1
T=N/Fs; %get the frequency interval
freq=k/T; %create the frequency range
X=fft(x)/N*2; % normalize the data
%only want the first half of the FFT, since it is redundant
cutOff = ceil(N/2);
%take only the first half of the spectrum
X = X(1:cutOff);
freq = freq(1:cutOff);`
by doing this, i made a magnitude spectrum of this rectangular wave, but only when the frequency is positive.
How can i plot a whole magnitude spectrum that includes negative frequencies??
If I understand you correctly, you want to obtain a vector of frequencies form -Fs/2 to Fs/2 and the corresponding magnitude of the spectrum. If so, you should use fftshift, for example:
N=length(x); %get the number of points
k=0:N-1; %create a vector from 0 to N-1
T=N/Fs; %get the frequency interval
freq=fftshift(k/T); %create the frequency range
X=fftshift(fft(x))/N*2; % normalize the data