Search code examples
matplotlibplotscipyoctave

Why are plots flipped when using freqz and comparing between Octave and SciPy?


When I plot response of these coefficients:

b=[1.01063287e+00, -1.46490341e+01,  9.94030209e+01, -4.19168764e+02, ...
  1.22949513e+03, -2.66000588e+03,  4.39112431e+03, -5.64225597e+03, ...
  5.70320516e+03, -4.55022454e+03,  2.85602975e+03, -1.39550096e+03, ...
  5.20372994e+02, -1.43160328e+02,  2.74037105e+01, -3.26098385e+00, ...
  1.81735269e-01];
a=[1.00000000e+00, -1.45159238e+01,  9.86464912e+01, -4.16614074e+02, ...
  1.22391361e+03, -2.65216678e+03,  4.38533779e+03, -5.64421414e+03, ...
  5.71487734e+03, -4.56742504e+03,  2.87187255e+03, -1.40575405e+03, ...
  5.25150201e+02, -1.44741759e+02,  2.77584882e+01, -3.30950845e+00, ...
  1.84797453e-01];

in Octave (which is OK):

pkg load signal
pkg load control

[h(:,1), w] = freqz(flip(b), flip(a),2048);
plot((w/pi),20*log10(abs(h(:,1))));

enter image description here

and in Python:

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import freqz

h = np.zeros(2048, float)
w = np.zeros(2048, float)

[h[:], w] = freqz(np.flip(b), np.flip(a), 2048)
  
plt.plot((w/np.pi),20*np.log10(h[:]));
plt.show()

enter image description here

, results are otherwise about equal but, as seen in plots, latter response is drawn something like twice turned compared to Octave's result.

What is going on and how to get equal plot with Octave from Python? I have tried by removing flip command from Python code but, response keeps being same.


Solution

  • scipy.signal.freqz returns (w,h), not (h,w) as you expect.

    This should work:

    w, h = freqz(np.flip(b), np.flip(a), 2048)
    
    plt.plot(w/np.pi,20*np.log10(np.abs(h)))
    plt.show()