Code covered by the BSD License  

Highlights from
MatLab Solutions: "Introduction to Digital Signal Processing: A Computer Laboratory Textbook".

image thumbnail

MatLab Solutions: "Introduction to Digital Signal Processing: A Computer Laboratory Textbook".

by

 

29 Oct 2012 (Updated )

These files are the MatLab solutions of exercises contained in the above DSP lab textbook.

my_spectrogram(x,Fs,N,M,win_type)
function  [K  S] = my_spectrogram(x,Fs,N,M,win_type)
% This function calculates the spectrogram of the input signal x.
% Inputs: x is a row vector that contains the signal to be analyzed.
%            Fs is the sampling frequency of x in Hz.
%            N is the selected length of the window in samples.
%            M is the selected ampount of overlap between successive windows in samples.
%            win_type is a string containing one of the windows shown
%            below. The default value of this variable corresponds to the rectangular window.
%
% Outputs: S is a matrix that contains the spectrogram of x. i.e. S = |STFT(x.*win)|^2.   
%                K is the number of length-N segments (windows) the whole signal has been divided to. 

switch win_type 
    
    case  'cheby'
       win = chebwin(N).';

    case 'blackman'
       win = blackman(N).';

    case 'hamm'
        win = hamming(N).';
        
    case 'hann'
         win = hanning(N).';  
        
    case 'kaiser'
         beta = 1;
         win = kaiser(N,beta).';  
         
    otherwise  % otherwise use the rectangular window
         win = ones(1,N);
end

L = length(x);
  
n = 0:N-1;
w = exp(-j*2*pi*n/N);
W = zeros(N,N);
for k=0:N-1
      W(:,k+1) = w.^k;
end

rows = N;
K = ceil((L-N)/(N-M))+1; % This is the number of segments the signal is divided to.
cols = K; 

% zero pad the tail of x as necessary in order to have an integer number of segments with length N.
if mod(L-N,N-M)
    x = [x zeros(1,N-mod(L-N,N-M))];
end

X = zeros(rows,cols);
for k=1:cols
     X(:,k) = x((k-1)*(N-M)+1:k*N - (k-1)*M).*win;
end
 
S = abs(W*X).^2;
         
if isreal(x)
   if ~mod(N,2)   % if N is even.
        S = S(1:N/2+2,:);
   else                 % if N is odd.
         S = S(1:(N-1)/2+2,:); 
   end
end            

Contact us