changing frequency using fft and ifft not using whole numbers - matlab

I know I can change frequency by whole numbers by changing the variable shift but how can I change the frequency using numbers with decimal places like .754 or 1.2345 or 67.456. If I change the variable 'shift' to a non-whole like number like 5.1 I get an error subscript indices must be either positive integers less than 2^31 or logicals from line mag2s = [mag2(shift+1:end), zeros(1,shift)];
Example Code below from question increase / decrease the frequency of a signal using fft and ifft in matlab / octave works with changing the variable shift (but it only works with whole numbers, I need it to work with decimals numbers also).
PS: I'm using octave 3.8.1 which is like matlab and I know I could change the frequency by adjusting the formula in the variable ya but ya will be a signal taken from an audio source (human speech) so it won't be an equation. The equation is just used to keep the example simple. And yes Fs is large due to the fact that signal files used are around 45 seconds long which is why I can't use resample because I get a out of memory error when used.
Here's a animated youtube video example of what I'm trying to get when I use the test equation ya= .5*sin(2*pi*1*t)+.2*cos(2*pi*3*t) and what I'm trying to get happen if I varied the variable shift from (0:0.1:5) youtu.be/pf25Gw6iS1U please keep in mind that ya will be an imported audio signal so I won't have an equation to easily adjust
clear all,clf
Fs = 2000000;% Sampling frequency
t=linspace(0,1,Fs);
%1a create signal
ya = .5*sin(2*pi*2*t);
%2a create frequency domain
ya_fft = fft(ya);
mag = abs(ya_fft);
phase = unwrap(angle(ya_fft));
ya_newifft=ifft(mag.*exp(i*phase));
% ----- changes start here ----- %
shift = 5; % shift amount
N = length(ya_fft); % number of points in the fft
mag1 = mag(2:N/2+1); % get positive freq. magnitude
phase1 = phase(2:N/2+1); % get positive freq. phases
mag2 = mag(N/2+2:end); % get negative freq. magnitude
phase2 = phase(N/2+2:end); % get negative freq. phases
% pad the positive frequency signals with 'shift' zeros on the left
% remove 'shift' components on the right
mag1s = [zeros(1,shift) , mag1(1:end-shift)];
phase1s = [zeros(1,shift) , phase1(1:end-shift)];
% pad the negative frequency signals with 'shift' zeros on the right
% remove 'shift' components on the left
mag2s = [mag2(shift+1:end), zeros(1,shift)];
phase2s = [phase2(shift+1:end), zeros(1,shift) ];
% recreate the frequency spectrum after the shift
% DC +ve freq. -ve freq.
magS = [mag(1) , mag1s , mag2s];
phaseS = [phase(1) , phase1s , phase2s];
x = magS.*cos(phaseS); % change from polar to rectangular
y = magS.*sin(phaseS);
yafft2 = x + i*y; % store signal as complex numbers
yaifft2 = real(ifft(yafft2)); % take inverse fft
plot(t,ya,'-r',t,yaifft2,'-b'); % time signal with increased frequency
legend('Original signal (ya) ','New frequency signal (yaifft2) ')

You can do this using a fractional delay filter.
First, lets make the code ore workable by letting Matlab handle the conjugate symmetry of the FFT. Just make mag1 and phase1 go to the end . . .
mag1 = mag(2:end);
phase1 = phase(2:end);
Get rid of mag2s and phase2s completely. This simplifies lines 37 and 38 to . .
magS = [mag(1) , mag1s ];
phaseS = [phase(1) , phase1s ];
Use the symmetric option of ifft to get Matlb to handle the symmetry for you. You can then drop the forced real, too.
yaifft2 = ifft(yafft2, 'symmetric'); % take inverse fft
With that cleaned up, we can now think of the delay as a filter, e.g.
% ----- changes start here ----- %
shift = 5;
shift_b = [zeros(1, shift) 1]; % shift amount
shift_a = 1;
which can be applied as so . . .
mag1s = filter(shift_b, shift_a, mag1);
phase1s = filter(shift_b, shift_a, phase1);
In this mindset, we can use an allpass filter to make a very simple fractional delay filter
The code above gives the 'M Samples Delay' part of the circuit. You can then add on the fraction using a second cascaded allpass filter . .
shift = 5.5;
Nw = floor(shift);
shift_b = [zeros(1, Nw) 1];
shift_a = 1;
Nf = mod(shift,1);
alpha = -(Nf-1)/(Nf+1);
fract_b = [alpha 1];
fract_a = [1 alpha];
%// now filter as a cascade . . .
mag1s = filter(shift_b, shift_a, mag1);
mag1s = filter(fract_b, fract_a, mag1s);

Ok so the question as I understand it is "how do I shift my signal by a specific frequency?"
First let's define Fs which is our sample rate (ie samples per second). We collect a signal which is N samples long. Then the frequency change between samples in the Fourier domain is Fs/N. So taking your example code Fs is 2,000,000 and N is 2,000,000 so the space between each sample is 1Hz and shifting your signal 5 samples shifts it 5Hz.
Now say we want to shift our signal by 5.25Hz instead. Well if our signal was 8,000,000 samples then the spacing would be Fs/N = 0.25Hz and we would shift our signal 11 samples. So how do we get an 8,000,000 sample signal from a 2,000,000 sample signal? Just zero pad it! literally append zeros until it is 8,000,000 samples long. Why does this work? Because you are in essence multiplying your signal by a rectangular window which is equivalent to sinc function convolution in the frequency domain. This is an important point. By appending zeros you are interpolating in the frequency domain (you don't have any more frequency information about the signal you are just interpolating between the previous DTFT points).
We can do this down to any resolution you want, but eventually you'll have to deal with the fact that numbers in digital systems aren't continuous so I recommend just choosing an acceptable tolerance. Lets say we want to be within 0.01 of our desired frequency.
So lets get to actual code. Most of it doesn't change luckily.
clear all,clf
Fs = 44100; % lets pick actual audio sampling rate
tolerance = 0.01; % our frequency bin tolerance
minSignalLen = Fs / tolerance; %minimum number of samples for our tolerance
%your code does not like odd length signals so lets make sure we have an
%even signal length
if(mod(minSignalLen,2) ~=0 )
minSignalLen = minSignalLen + 1;
end
t=linspace(0,1,Fs); %our input signal is 1s long
%1a create 2Hz signal
ya = .5*sin(2*pi*2*t);
if (length(ya) < minSignalLen)
ya = [ya, zeros(1, minSignalLen - length(ya))];
end
df = Fs / length(ya); %actual frequency domain spacing;
targetFreqShift = 2.32; %lets shift it 2.32Hz
nSamplesShift = round(targetFreqShift / df);
%2a create frequency domain
ya_fft = fft(ya);
mag = abs(ya_fft);
phase = unwrap(angle(ya_fft));
ya_newifft=ifft(mag.*exp(i*phase));
% ----- changes start here ----- %
shift = nSamplesShift; % shift amount
N = length(ya_fft); % number of points in the fft
mag1 = mag(2:N/2+1); % get positive freq. magnitude
phase1 = phase(2:N/2+1); % get positive freq. phases
mag2 = mag(N/2+2:end); % get negative freq. magnitude
phase2 = phase(N/2+2:end); % get negative freq. phases
% pad the positive frequency signals with 'shift' zeros on the left
% remove 'shift' components on the right
mag1s = [zeros(1,shift) , mag1(1:end-shift)];
phase1s = [zeros(1,shift) , phase1(1:end-shift)];
% pad the negative frequency signals with 'shift' zeros on the right
% remove 'shift' components on the left
mag2s = [mag2(shift+1:end), zeros(1,shift)];
phase2s = [phase2(shift+1:end), zeros(1,shift) ];
% recreate the frequency spectrum after the shift
% DC +ve freq. -ve freq.
magS = [mag(1) , mag1s , mag2s];
phaseS = [phase(1) , phase1s , phase2s];
x = magS.*cos(phaseS); % change from polar to rectangular
y = magS.*sin(phaseS);
yafft2 = x + i*y; % store signal as complex numbers
yaifft2 = real(ifft(yafft2)); % take inverse fft
%pull out the original 1s of signal
plot(t,ya(1:length(t)),'-r',t,yaifft2(1:length(t)),'-b');
legend('Original signal (ya) ','New frequency signal (yaifft2) ')
The final signal is a little over 4Hz which is what we expect. There is some distortion visible from the interpolation, but that should be minimized with a longer signal with a smother frequency domain representation.
Now that I've gone through all of that you may be wondering if there is an easier way. Fortunately for us, there is. We can take advantage of the hilbert transform and fourier transform properties to achieve a frequency shift without ever worrying about Fs or tolerance levels or bin spacing. Namely we know that a time shift leads to a phase shift in the Fourier domain. Well time and frequency are duals so a frequency shift leads to a complex exponential multiplication in the time domain. We don't want to just do a bulk shift of all frequencies because that that will ruin our symmetry in Fourier space leading to a complex time series. So we use the hilbert transform to get the analytic signal which is composed of only the positive frequencies, shift that, and then reconstruct our time series assuming a symmetric Fourier representation.
Fs = 44100;
t=linspace(0,1,Fs);
FShift = 2.3 %shift our frequency up by 2.3Hz
%1a create signal
ya = .5*sin(2*pi*2*t);
yaHil = hilbert(ya); %get the hilbert transform
yaShiftedHil = yaHil.*exp(1i*2*pi*FShift*t);
yaShifted = real(yaShiftedHil);
figure
plot(t,ya,'-r',t,yaShifted,'-b')
legend('Original signal (ya) ','New frequency signal (yaifft2) ')

Band-limited interpolation using a windowed-Sinc interpolation kernel can be used to change sample rate by arbitrary ratios. Changing the sample rate changes the frequency content of the signal, relative to the sample rate, by the inverse ratio.

Related

How do I create band-limited (100-640 Hz) white Gaussian noise?

I would like to create 500 ms of band-limited (100-640 Hz) white Gaussian noise with a (relatively) flat frequency spectrum. The noise should be normally distributed with mean = ~0 and 99.7% of values between ± 2 (i.e. standard deviation = 2/3). My sample rate is 1280 Hz; thus, a new amplitude is generated for each frame.
duration = 500e-3;
rate = 1280;
amplitude = 2;
npoints = duration * rate;
noise = (amplitude/3)* randn( 1, npoints );
% Gaus distributed white noise; mean = ~0; 99.7% of amplitudes between ± 2.
time = (0:npoints-1) / rate
Could somebody please show me how to filter the signal for the desired result (i.e. 100-640 Hz)? In addition, I was hoping somebody could also show me how to generate a graph to illustrate that the frequency spectrum is indeed flat.
I intend on importing the waveform to Signal (CED) to output as a form of transcranial electrical stimulation.
The following is Matlab implementation of the method alluded to by "Some Guy" in a comment to your question.
% In frequency domain, white noise has constant amplitude but uniformly
% distributed random phase. We generate this here. Only half of the
% samples are generated here, the rest are computed later using the complex
% conjugate symmetry property of the FFT (of real signals).
X = [1; exp(i*2*pi*rand(npoints/2-1,1)); 1]; % X(1) and X(NFFT/2) must be real
% Identify the locations of frequency bins. These will be used to zero out
% the elements of X that are not in the desired band
freqbins = (0:npoints/2)'/npoints*rate;
% Zero out the frequency components outside the desired band
X(find((freqbins < 100) | (freqbins > 640))) = 0;
% Use the complex conjugate symmetry property of the FFT (for real signals) to
% generate the other half of the frequency-domain signal
X = [X; conj(flipud(X(2:end-1)))];
% IFFT to convert to time-domain
noise = real(ifft(X));
% Normalize such that 99.7% of the times signal lies between ±2
noise = 2*noise/prctile(noise, 99.7);
Statistical analysis of around a million samples generated using this method results in the following spectrum and distribution:
Firstly, the spectrum (using Welch method) is, as expected, flat in the band of interest:
Also, the distribution, estimated using histogram of the signal, matches the Gaussian PDF quite well.

Finding peak frequency in a complex signal using Matlab

I'm trying to find the peak frequency for two signals 'CA1' and 'PFC', within a specified range (25-140Hz).
In Matlab, so far I have plotted an FFT for each of these signals (see pictures below). These FFTs suggest that the peak frequency between 25-140Hz is different for each signal, but I would like to quantify this (e.g. CA1 peaks at 80Hz, whereas PFC peaks at 55Hz). However, I think the FFT is not smooth enough, so when I try and extract the peak frequencies it doesn't make sense as my code pulls out loads of values. I was only expecting a few values - one each time the FFT peaks (around 2Hz, 5Hz and ~60Hz).
I want to know, between 25-140Hz, what is the peak frequency in 'CA1' compared with 'PFC'. 'CA1' and 'PFC' are both 152401 x 7 matrices of EEG data, recorded
from 7 separate individuals. I want the MEAN peak frequency for each data set (i.e. averaged across the 7 test subjects for CA1 and PFC).
My code so far (based on Matlab help files and code I've scrabbled together online):
Fs = 508;
%notch filter
[b50,a50] = iirnotch(50/(Fs/2), (50/(Fs/2))/70);
CA1 = filtfilt(b50,a50,CA1);
PFC = filtfilt(b50,a50,PFC);
%FFT
L = length(CA1);
NFFT = 2^nextpow2(L);
%FFT for each of the 7 subjects
for i = 1:size(CA1,2);
CA1_FFT(:,i) = fft(CA1(:,i),NFFT)/L;
PFC_FFT(:,i) = fft(PFC(:,i),NFFT)/L;
end
%Average FFT across all 7 subjects - CA1
Mean_CA1_FFT = mean(CA1_FFT,2);
% Mean_CA1_FFT_abs = 2*abs(Mean_CA1_FFT(1:NFFT/2+1));
%Average FFT across all 7 subjects - PFC
Mean_PFC_FFT = mean(PFC_FFT,2);
% Mean_PFC_FFT_abs = 2*abs(Mean_PFC_FFT(1:NFFT/2+1));
f = Fs/2*linspace(0,1,NFFT/2+1);
%LEFT HAND SIDE FIGURE
plot(f,2*abs(Mean_CA1_FFT(1:NFFT/2+1)),'r');
set(gca,'ylim', [0 2]);
set(gca,'xlim', [0 200]);
[C,cInd] = sort(2*abs(Mean_CA1_FFT(1:NFFT/2+1)));
CFloor = 0.1; %CFloor is the minimum amplitude value (ignore small values)
Amplitudes_CA1 = C(C>=CFloor); %find all amplitudes above the CFloor
Frequencies_CA1 = f(cInd(1+end-numel(Amplitudes_CA1):end)); %frequency of the peaks
%RIGHT HAND SIDE FIGURE
figure;plot(f,2*abs(Mean_PFC_FFT(1:NFFT/2+1)),'r');
set(gca,'ylim', [0 2]);
set(gca,'xlim', [0 200]);
[P,pInd] = sort(2*abs(Mean_PFC_FFT(1:NFFT/2+1)));
PFloor = 0.1; %PFloor is the minimum amplitude value (ignore small values)
Amplitudes_PFC = P(P>=PFloor); %find all amplitudes above the PFloor
Frequencies_PFC = f(pInd(1+end-numel(Amplitudes_PFC):end)); %frequency of the peaks
Please help!! How do I calculate the 'major' peak frequencies from an FFT, and ignore all the 'minor' peaks (because the FFT is not smoothed).
FFTs assume that the signal has no trend (this is called a stationary signal), if it does then this will give a dominant frequency component at 0Hz as you have here. Try using the MATLAB function detrend, you may find this solves your problem.
Something along the lines of:
x = x - mean(x)
y = detrend(x, 'constant')

identifying phase shift between signals

I have generated three identical waves with a phase shift in each. For example:
t = 1:10800; % 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).
y1 = A*sin(2*pi*f1*t); % signal 1
phi = 10; % phase shift
y2 = A*sin(2*pi*f1*t + phi); % signal 2
phi = 15; % phase shift
y3 = A*sin(2*pi*f1*t + phi); % signal 3
YY = [y1',y2',y3'];
plot(t,YY)
I would now like to use a method for detecting this phase shift between the waves. The point of doing this is so that I can eventually apply the method to real data and identify phase shifts between signals.
So far I have been thinking of computing the cross spectra between each wave and the first wave (i.e. without the phase shift):
for i = 1:3;
[Pxy,Freq] = cpsd(YY(:,1),YY(:,i));
coP = real(Pxy);
quadP = imag(Pxy);
phase(:,i) = atan2(coP,quadP);
end
but I'm not sure if this makes any sense.
Has anyone else done something similar to this? The desired outcome should show a phase shift at 10 and 15 for waves 2 and 3 respectively.
Any advice would be appreciated.
There are several ways that you can measure the phase shift between signals. Between your response, the comments below your response, and the other answers, you've gotten most of the options. The specific choice of technique is usually based on issues such as:
Noisy or Clean: Is there noise in your signal?
Multi-Component or Single-Component: Are there more than one type of signal within your recording (multiple tones at multiple frequencies moving in different directions)? Or, is there just a single signal, like in your sine-wave example?
Instantaneous or Averaged: Are you looking for the average phase lag across your entire recording, or are you looking to track how the phase changes throughout the recording?
Depending on your answer to these questions, you could consider the following techniques:
Cross-Correlation: Use the a command like [c,lag]=xcorr(y1,y2); to get the cross-correlation between the two signals. This works on the original time-domain signals. You look for the index where c is maximum ([maxC,I]=max(c);) and then you get your lag value in units of samples lag = lag(I);. This approach gives you the average phase lag for the entire recording. It requires that your signal of interest in the recording be stronger than anything else in your recording...in other words, it is sensitive to noise and other interference.
Frequency Domain: Here you convert your signals into the frequency domain (using fft or cpsd or whatever). Then, you'd find the bin that corresponds to the frequency that you care about and get the angle between the two signals. So, for example, if bin #18 corresponds to your signal's frequency, you'd get the phase lag in radians via phase_rad = angle(fft_y1(18)/fft_y2(18));. If your signals have a constant frequency, this is an excellent approach because it naturally rejects all noise and interference at other frequencies. You can have really strong interference at one frequency, but you can still cleanly get your signal at another frequency. This technique is not the best for signals that change frequency during the fft analysis window.
Hilbert Transform: A third technique, often overlooked, is to convert your time-domain signal into an analytic signal via the Hilbert transform: y1_h = hilbert(y1);. Once you do this, your signal is a vector of complex numbers. A vector holding a simple sine wave in the time domain will now be a vector of complex numbers whose magnitude is constant and whose phase is changing in sync with your original sine wave. This technique allows you to get the instantaneous phase lag between two signals...it's powerful: phase_rad = angle(y1_h ./ y2_h); or phase_rad = wrap(angle(y1_h) - angle(y2_h));. The major limitation to this approach is that your signal needs to be mono-component, meaning that your signal of interest must dominate your recording. Therefore, you may have to filter out any substantial interference that might exist.
For two sinusoidal signal the phase of the complex correlation coefficient gives you what you want. I can only give you an python example (using scipy) as I don't have a matlab to test it.
x1 = sin( 0.1*arange(1024) )
x2 = sin( 0.1*arange(1024) + 0.456)
x1h = hilbert(x1)
x2h = hilbert(x2)
c = inner( x1h, conj(x2h) ) / sqrt( inner(x1h,conj(x1h)) * inner(x2h,conj(x2h)) )
phase_diff = angle(c)
There is a function corrcoeff in matlab, that should work, too (The python one discard the imaginary part). I.e. c = corrcoeff(x1h,x2h) should work in matlab.
The Matlab code to find relative phase using cross-correlation:
fr = 20; % input signal freq
timeStep = 1e-4;
t = 0:timeStep:50; % time vector
y1 = sin(2*pi*t); % reference signal
ph = 0.5; % phase difference to be detected in radians
y2 = 0.9 * sin(2*pi*t + ph); % signal, the phase of which, is to be measured relative to the reference signal
[c,lag]=xcorr(y1,y2); % calc. cross-corel-n
[maxC,I]=max(c); % find max
PH = (lag(I) * timeStep) * 2 * pi; % calculated phase in radians
>> PH
PH =
0.4995
With the correct signals:
t = 1:10800; % 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).
y1 = A*sin(2*pi*f1*t); % signal 1
phi = 10*pi/180; % phase shift in radians
y2 = A*sin(2*pi*f1*t + phi); % signal 2
phi = 15*pi/180; % phase shift in radians
y3 = A*sin(2*pi*f1*t + phi); % signal 3
The following should work:
>> acos(dot(y1,y2)/(norm(y1)*norm(y2)))
>> ans*180/pi
ans = 9.9332
>> acos(dot(y1,y3)/(norm(y1)*norm(y3)))
ans = 0.25980
>> ans*180/pi
ans = 14.885
Whether or not that's good enough for your "real" signals, only you can tell.
Here is the little modification of your code: phi = 10 is actually in degree, then in sine function, phase information is mostly expressed in radian,so you need to change deg2rad(phi) as following:
t = 1:10800; % 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).
y1 = A*sin(2*pi*f1*t); % signal 1
phi = deg2rad(10); % phase shift
y2 = A*sin(2*pi*f1*t + phi); % signal 2
phi = deg2rad(15); % phase shift
y3 = A*sin(2*pi*f1*t + phi); % signal 3
YY = [y1',y2',y3'];
plot(t,YY)
then using frequency domain method as mentioned chipaudette
fft_y1 = fft(y1);
fft_y2 = fft(y2);
phase_rad = angle(fft_y1(1:end/2)/fft_y2(1:end/2));
phase_deg = rad2deg(angle(fft_y1(1:end/2)/fft_y2(1:end/2)));
now this will give you a phase shift estimate with error = +-0.2145
If you know the frequency and just want to find the phase, rather than use a full FFT, you might want to consider the Goertzel algorithm, which is a more efficient way to calculate the DFT for a single frequency (an FFT will calculate it for all frequencies).
For a good implementation, see: https://www.mathworks.com/matlabcentral/fileexchange/35103-generalized-goertzel-algorithm and https://asp-eurasipjournals.springeropen.com/track/pdf/10.1186/1687-6180-2012-56.pdf
If you use an AWGN signal with delay and apply your method it works, but if you are using a single tone frequency estimation will not help you. because there is no energy in any other frequency but the tone. You better use cross-correlation in the time domain for this - it will work better for a fixed delay. If you have a wideband signal you can use subbands domain and estimate the phase from that (it is better than FFT due to low cross-frequency dependencies).

frequency domain interpolation changes the signal spectrum

I am working on some experimental data related to a sine-sweep excitation.
I first reconstructed the signal using the amplitude and frequency information I get from the data file:
% finz: frequency
% ginz: amplitude
R = 4; % sweep rate
tz = 60/R*log2(finz/finz(1)); % time
u_swt = sin(2*pi*((60*finz(1)/(R*log(2.))*(2.^(R/60*tz)-1))));
time_sign = ginz.*u_swt;
freq_sign = fft(time_sign);
This is what I obtain:
I then tried to interpolate the frequency data before computing the time signal to obtain a 'nicer' signal (having more samples it should be easier to reconstruct it):
ginz = interp(ginz,200);
finz = interp(finz,200);
But now the spectrum is changed:
Why the frequency spectrum is so different? Am I doing something wrong in the interpolation? Should I not interpolate the data?
The details of the signal you are working with are not clear to me. For instance, can you please provide typical examples of finz and ginz? Also, it is not clear what you are hoping to achieve through interpolation, so it is hard to advise on its use.
However, if you interpolate a time series you should expect its spectrum to change as it increases the sampling frequency. The frequency of an interpolated signal will become smaller relative to the new sampling frequency. Therefore, the signal spectrum will be (not being very technical here) pushed towards zero. I have provided a script below which creates white Gaussian noise, and plots the spectrum for different levels of interpolation. In the first subfigure with no interpolation, the spectrum is uniformly occupied (by design - white noise). In subsequent subfigures, with increasing interpolation the occupied spectrum becomes smaller and smaller. Hope this helps.
% white Gaussian noise (WGN)
WGN = randn(1,1000);
% DFT of WGN
DFT_WGN = abs(fft(WGN));
% one-sided spectrum
DFT_WGN = DFT_WGN(1:length(WGN)/2);
% interpolated WGN by factor of 2 (q = 2)
WGN_interp_2 = interp(WGN,2);
% DFT of interpolated WGN
DFT_WGN_interp_2 = abs(fft(WGN_interp_2));
% one-sided spectrum
DFT_WGN_interp_2 = DFT_WGN_interp_2(1:length(DFT_WGN_interp_2 )/2);
% interpolated WGN by factor of 10 (q = 10)
WGN_interp_10 = interp(WGN,10);
% DFT of interpolated WGN
DFT_WGN_interp_10 = abs(fft(WGN_interp_10));
% one-sided spectrum
DFT_WGN_interp_10 = DFT_WGN_interp_10(1:length(DFT_WGN_interp_10 )/2);
figure
subplot(3,1,1)
plot(DFT_WGN)
ylabel('DFT')
subplot(3,1,2)
plot(DFT_WGN_interp_2)
ylabel('DFT (q:2)')
subplot(3,1,3)
plot(DFT_WGN_interp_10)
ylabel('DFT (q:10)')

Spectrogram and what it is

I am very interested to know how the top right figure in :http://en.wikipedia.org/wiki/Spectrogram
is generated (the script) and how to analyse it i.e what information does it convey?I would appreciate a simplified answer with minimum mathematical jargons. Thank you.
The plot shows time along the horizontal axis, and frequency along the vertical axis. With pixel color showing the intensity of each frequency at each time.
A spectrogram is generated by taking a signal and chopping it into small time segments, doing a Fourier series on each segment.
here is some matlab code to generate one.
Notice how plotting the signal directly, it looks like garbage, but plotting the spectrogram, we can clearly see the frequencies of the component signals.
%%%%%%%%
%% setup
%%%%%%%%
%signal length in seconds
signalLength = 60+10*randn();
%100Hz sampling rate
sampleRate = 100;
dt = 1/sampleRate;
%total number of samples, and all time tags
Nsamples = round(sampleRate*signalLength);
time = linspace(0,signalLength,Nsamples);
%%%%%%%%%%%%%%%%%%%%%
%create a test signal
%%%%%%%%%%%%%%%%%%%%%
%function for converting from time to frequency in this test signal
F1 = #(T)0+40*T/signalLength; #frequency increasing with time
M1 = #(T)1-T/signalLength; #amplitude decreasing with time
F2 = #(T)20+10*sin(2*pi()*T/signalLength); #oscilating frequenct over time
M2 = #(T)1/2; #constant low amplitude
%Signal frequency as a function of time
signal1Frequency = F1(time);
signal1Mag = M1(time);
signal2Frequency = F2(time);
signal2Mag = M2(time);
%integrate frequency to get angle
signal1Angle = 2*pi()*dt*cumsum(signal1Frequency);
signal2Angle = 2*pi()*dt*cumsum(signal2Frequency);
%sin of the angle to get the signal value
signal = signal1Mag.*sin(signal1Angle+randn()) + signal2Mag.*sin(signal2Angle+randn());
figure();
plot(time,signal)
%%%%%%%%%%%%%%%%%%%%%%%
%processing starts here
%%%%%%%%%%%%%%%%%%%%%%%
frequencyResolution = 1
%time resolution, binWidth, is inversly proportional to frequency resolution
binWidth = 1/frequencyResolution;
%number of resulting samples per bin
binSize = sampleRate*binWidth;
%number of bins
Nbins = ceil(Nsamples/binSize);
%pad the data with zeros so that it fills Nbins
signal(Nbins*binSize+1)=0;
signal(end) = [];
%reshape the data to binSize by Nbins
signal = reshape(signal,[binSize,Nbins]);
%calculate the fourier transform
fourierResult = fft(signal);
%convert the cos+j*sin, encoded in the complex numbers into magnitude.^2
mags= fourierResult.*conj(fourierResult);
binTimes = linspace(0,signalLength,Nbins);
frequencies = (0:frequencyResolution:binSize*frequencyResolution);
frequencies = frequencies(1:end-1);
%the upper frequencies are just aliasing, you can ignore them in this example.
slice = frequencies<max(frequencies)/2;
%plot the spectrogram
figure();
pcolor(binTimes,frequencies(slice),mags(slice,:));
The inverse Fourier transform of the fourierResult matrix, will return the original signal.
Just to add to Suki's answer, here is a great tutorial that walks you through, step by step, reading Matlab spectrograms, touching on only enough math and physics to explain the main concepts intuitively:
http://www.caam.rice.edu/~yad1/data/EEG_Rice/Literature/Spectrograms.pdf