Search code examples
matlabplotspectrumspectrogram

Plotting Frequency Spectrum using Matlab with hold function


Suppose I have successfully generated a Single-sided Power spectrum as follows:

X_mags = abs(fft(signal));
bin_vals = [0 : N-1];
fax_Hz = bin_vals*fs/N;
N_2 = ceil(N/2);
plot(fax_Hz(1:N_2), 20*log10(X_mags(1:N_2)));`

now I want to plot a second graph on top of the first one:

hold on;

Lastly I perform an LPC analysis on the signal and calculate the frequency response. The frequency response should be plotted on top of the Power spectrum, so:

[a, g] = lpc(signal,N);
[h,f] = freqz(b,a,N,fs);
plot(?);

For the sake of simplicity, let's assume the parameters are all correctly given, how should I write the plot function for having a correct display of the frequency response? A simple plot(f) doesn't work.

Can someone explain why? Thanks


Solution

  • A simple plot(f) tries to plot frequency vector, isn' t it?

    Check the code below:

    X_mags   = abs(fft(signal));
    bin_vals = [0 : N-1];
    fax_Hz   = bin_vals*fs/N;
    N_2      = ceil(N/2);
    
    [a, g]   = lpc(signal,N);
    [h, f]   = freqz(b, a, N, fs);
    
    figure,
    
    hold on,
    plot(f, 20*log10(abs(h)), 'r');
    plot(fax_Hz(1:N_2), 20*log10(X_mags(1:N_2)));
    title('Frequency Spectrum');
    xlabel('Frequency (Hz)'); 
    ylabel('Amplitude (dB)');
    legend('Frequency Response', 'Single-sided Power spectrum')
    

    Btw, there is a MATLAB function db() for decibel calculation. That might be useful.