1 ## Copyright (C) 2000 Paul Kienzle <pkienzle@users.sf.net>
2 ## Copyright (C) 2004 Julius O. Smith III <jos@ccrma.stanford.edu>
4 ## This program is free software; you can redistribute it and/or modify it under
5 ## the terms of the GNU General Public License as published by the Free Software
6 ## Foundation; either version 3 of the License, or (at your option) any later
9 ## This program is distributed in the hope that it will be useful, but WITHOUT
10 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14 ## You should have received a copy of the GNU General Public License along with
15 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## Compute the group delay of a filter.
19 ## [g, w] = grpdelay(b)
20 ## returns the group delay g of the FIR filter with coefficients b.
21 ## The response is evaluated at 512 angular frequencies between 0 and
22 ## pi. w is a vector containing the 512 frequencies.
23 ## The group delay is in units of samples. It can be converted
24 ## to seconds by multiplying by the sampling period (or dividing by
25 ## the sampling rate fs).
27 ## [g, w] = grpdelay(b,a)
28 ## returns the group delay of the rational IIR filter whose numerator
29 ## has coefficients b and denominator coefficients a.
31 ## [g, w] = grpdelay(b,a,n)
32 ## returns the group delay evaluated at n angular frequencies. For fastest
33 ## computation n should factor into a small number of small primes.
35 ## [g, w] = grpdelay(b,a,n,'whole')
36 ## evaluates the group delay at n frequencies between 0 and 2*pi.
38 ## [g, f] = grpdelay(b,a,n,Fs)
39 ## evaluates the group delay at n frequencies between 0 and Fs/2.
41 ## [g, f] = grpdelay(b,a,n,'whole',Fs)
42 ## evaluates the group delay at n frequencies between 0 and Fs.
44 ## [g, w] = grpdelay(b,a,w)
45 ## evaluates the group delay at frequencies w (radians per sample).
47 ## [g, f] = grpdelay(b,a,f,Fs)
48 ## evaluates the group delay at frequencies f (in Hz).
51 ## plots the group delay vs. frequency.
53 ## If the denominator of the computation becomes too small, the group delay
54 ## is set to zero. (The group delay approaches infinity when
55 ## there are poles or zeros very close to the unit circle in the z plane.)
57 ## Theory: group delay, g(w) = -d/dw [arg{H(e^jw)}], is the rate of change of
58 ## phase with respect to frequency. It can be computed as:
61 ## g(w) = -------------
65 ## H(z) = B(z)/A(z) = sum(b_k z^k)/sum(a_k z^k).
67 ## By the quotient rule,
68 ## A(z) d/dw B(z) - B(z) d/dw A(z)
69 ## d/dw H(z) = -------------------------------
71 ## Substituting into the expression above yields:
73 ## g(w) = ----------- = dB/B - dA/A
77 ## d/dw B(e^-jw) = sum(k b_k e^-jwk)
78 ## d/dw A(e^-jw) = sum(k a_k e^-jwk)
79 ## which is just the FFT of the coefficients multiplied by a ramp.
81 ## As a further optimization when nfft>>length(a), the IIR filter (b,a)
82 ## is converted to the FIR filter conv(b,fliplr(conj(a))).
83 ## For further details, see
84 ## http://ccrma.stanford.edu/~jos/filters/Numerical_Computation_Group_Delay.html
86 function [gd,w] = grpdelay(b,a=1,nfft=512,whole,Fs)
88 if (nargin<1 || nargin>5)
95 elseif nargin>3 % grpdelay(B,A,F,Fs)
98 else % grpdelay(B,A,W)
106 Fs=1; % return w in radians per sample
107 if nargin<4, whole='';
108 elseif ~ischar(whole)
113 if nargin<3, nfft=512; end
114 if nargin<2, a=1; end
119 if isempty(nfft), nfft = 512; end
120 if ~strcmp(whole,'whole'), nfft = 2*nfft; end
121 w = Fs*[0:nfft-1]/nfft;
124 if ~HzFlag, w = w * 2*pi; end
126 oa = length(a)-1; % order of a(z)
127 if oa<0, a=1; oa=0; end % a can be []
128 ob = length(b)-1; % order of b(z)
129 if ob<0, b=1; ob=0; end % b can be [] as well
130 oc = oa + ob; % order of c(z)
132 c = conv(b,fliplr(conj(a))); % c(z) = b(z)*conj(a)(1/z)*z^(-oa)
133 cr = c.*[0:oc]; % cr(z) = derivative of c wrt 1/z
137 polebins = find(abs(den)<minmag);
139 warning('grpdelay: setting group delay to 0 at singularity');
142 % try to preserve angle:
144 % den(b) = minmag*abs(num(b))*exp(j*atan2(imag(db),real(db)));
145 % warning(sprintf('grpdelay: den(b) changed from %f to %f',db,den(b)));
147 gd = real(num ./ den) - oa;
149 if strcmp(whole,'whole')==0
150 ns = nfft/2; % Matlab convention ... should be nfft/2 + 1
154 ns = nfft; % used in plot below
158 gd = gd(:); w = w(:);
162 grid('on'); % grid() should return its previous state
166 funits = 'radian/sample';
168 xlabel(['Frequency (', funits, ')']);
169 ylabel('Group delay (samples)');
170 plot(w(1:ns), gd(1:ns), ';;');
171 unwind_protect_cleanup
177 % ------------------------ DEMOS -----------------------
180 %! %--------------------------------------------------------------
181 %! % From Oppenheim and Schafer, a single zero of radius r=0.9 at
182 %! % angle pi should have a group delay of about -9 at 1 and 1/2
183 %! % at zero and 2*pi.
184 %! %--------------------------------------------------------------
185 %! title ('Zero at z = -0.9');
186 %! grpdelay([1 0.9],[],512,'whole',1);
188 %! xlabel('Normalized Frequency (cycles/sample)');
189 %! stem([0, 0.5, 1],[0.5, -9, 0.5],'*b;target;');
193 %! %--------------------------------------------------------------
194 %! % confirm the group delays approximately meet the targets
195 %! % don't worry that it is not exact, as I have not entered
196 %! % the exact targets.
197 %! %--------------------------------------------------------------
198 %! b = poly([1/0.9*exp(1i*pi*0.2), 0.9*exp(1i*pi*0.6)]);
199 %! a = poly([0.9*exp(-1i*pi*0.6), 1/0.9*exp(-1i*pi*0.2)]);
200 %! title ('Two Zeros and Two Poles');
201 %! grpdelay(b,a,512,'whole',1);
203 %! xlabel('Normalized Frequency (cycles/sample)');
204 %! stem([0.1, 0.3, 0.7, 0.9], [9, -9, 9, -9],'*b;target;');
208 %! %--------------------------------------------------------------
209 %! % fir lowpass order 40 with cutoff at w=0.3 and details of
210 %! % the transition band [.3, .5]
211 %! %--------------------------------------------------------------
213 %! Fs = 8000; % sampling rate
214 %! Fc = 0.3*Fs/2; % lowpass cut-off frequency
216 %! b = fir1(nb,2*Fc/Fs); % matlab freq normalization: 1=Fs/2
217 %! [H,f] = freqz(b,1,[],1);
218 %! [gd,f] = grpdelay(b,1,[],1);
219 %! title(sprintf('b = fir1(%d,2*%d/%d);',nb,Fc,Fs));
220 %! xlabel('Normalized Frequency (cycles/sample)');
221 %! ylabel('Amplitude Response (dB)');
223 %! plot(f,20*log10(abs(H)));
225 %! del = nb/2; % should equal this
226 %! title(sprintf('Group Delay in Pass-Band (Expect %d samples)',del));
227 %! ylabel('Group Delay (samples)');
228 %! axis([0, 0.2, del-1, del+1]);
233 %! %--------------------------------------------------------------
234 %! % IIR bandstop filter has delays at [1000, 3000]
235 %! %--------------------------------------------------------------
237 %! [b, a] = cheby1(3, 3, 2*[1000, 3000]/Fs, 'stop');
238 %! [H,f] = freqz(b,a,[],Fs);
239 %! [gd,f] = grpdelay(b,a,[],Fs);
241 %! title('[b,a] = cheby1(3, 3, 2*[1000, 3000]/Fs, \'stop\');');
242 %! xlabel('Frequency (Hz)');
243 %! ylabel('Amplitude Response');
247 %! title('[gd,f] = grpdelay(b,a,[],Fs);');
248 %! ylabel('Group Delay (samples)');
252 % ------------------------ TESTS -----------------------
255 %! [gd1,w] = grpdelay([0,1]);
256 %! [gd2,w] = grpdelay([0,1],1);
257 %! assert(gd1,gd2,10*eps);
260 %! [gd,w] = grpdelay([0,1],1,4);
261 %! assert(gd,[1;1;1;1]);
262 %! assert(w,pi/4*[0:3]',10*eps);
265 %! [gd,w] = grpdelay([0,1],1,4,'whole');
266 %! assert(gd,[1;1;1;1]);
267 %! assert(w,pi/2*[0:3]',10*eps);
270 %! [gd,f] = grpdelay([0,1],1,4,0.5);
271 %! assert(gd,[1;1;1;1]);
272 %! assert(f,1/16*[0:3]',10*eps);
275 %! [gd,w] = grpdelay([0,1],1,4,'whole',1);
276 %! assert(gd,[1;1;1;1]);
277 %! assert(w,1/4*[0:3]',10*eps);
280 %! [gd,f] = grpdelay([1 -0.9j],[],4,'whole',1);
281 %! gd0 = 0.447513812154696; gdm1 =0.473684210526316;
282 %! assert(gd,[gd0;-9;gd0;gdm1],20*eps);
283 %! assert(f,1/4*[0:3]',10*eps);
286 %! gd= grpdelay(1,[1,.9],2*pi*[0,0.125,0.25,0.375]);
287 %! assert(gd, [-0.47368;-0.46918;-0.44751;-0.32316],1e-5);
290 %! gd= grpdelay(1,[1,.9],[0,0.125,0.25,0.375],1);
291 %! assert(gd, [-0.47368;-0.46918;-0.44751;-0.32316],1e-5);
294 %! gd = grpdelay([1,2],[1,0.5,.9],4);
295 %! assert(gd,[-0.29167;-0.24218;0.53077;0.40658],1e-5);
298 %! b1=[1,2];a1f=[0.25,0.5,1];a1=fliplr(a1f);
299 %! % gd1=grpdelay(b1,a1,4);
300 %! gd=grpdelay(conv(b1,a1f),1,4)-2;
301 %! assert(gd, [0.095238;0.239175;0.953846;1.759360],1e-5);
305 %! [b, a] = cheby1(3, 3, 2*[1000, 3000]/Fs, 'stop');
306 %! [h, w] = grpdelay(b, a, 256, 'half', Fs);
307 %! [h2, w2] = grpdelay(b, a, 512, 'whole', Fs);
308 %! assert (size(h), size(w));
309 %! assert (length(h), 256);
310 %! assert (size(h2), size(w2));
311 %! assert (length(h2), 512);
312 %! assert (h, h2(1:256));
313 %! assert (w, w2(1:256));
318 %! [dh, wf] = grpdelay(b, a, 512, 'whole');
319 %! [da, wa] = grpdelay(1, a, 512, 'whole');
320 %! [db, wb] = grpdelay(b, 1, 512, 'whole');
321 %! assert(dh,db+da,1e-5);