1 %% Copyright (C) 1986,2003 Julius O. Smith III <jos@ccrma.stanford.edu>
2 %% Copyright (C) 2003 Andrew Fitting
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 %% usage: [B,A] = invfreqz(H,F,nB,nA)
18 %% [B,A] = invfreqz(H,F,nB,nA,W)
19 %% [B,A] = invfreqz(H,F,nB,nA,W,iter,tol,'trace')
21 %% Fit filter B(z)/A(z)to the complex frequency response H at frequency
22 %% points F. A and B are real polynomial coefficients of order nA and nB.
23 %% Optionally, the fit-errors can be weighted vs frequency according to
25 %% Note: all the guts are in invfreq.m
27 %% H: desired complex frequency response
28 %% F: normalized frequncy (0 to pi) (must be same length as H)
29 %% nA: order of the denominator polynomial A
30 %% nB: order of the numerator polynomial B
31 %% W: vector of weights (must be same length as F)
34 %% [B,A] = butter(4,1/4);
35 %% [H,F] = freqz(B,A);
36 %% [Bh,Ah] = invfreq(H,F,4,4);
38 %% disp(sprintf('||frequency response error|| = %f',norm(H-Hh)));
40 %% TODO: check invfreq.m for todo's
42 function [B, A, SigN] = invfreqz(H, F, nB, nA, W, iter, tol, tr, varargin)
53 W = ones(1,length(F));
61 % now for the real work
62 [B, A, SigN] = invfreq(H, F, nB, nA, W, iter, tol, tr, 'z', varargin{:});
67 %! order = 9; % order of test filter
68 %! % going to 10 or above leads to numerical instabilities and large errors
69 %! fc = 1/2; % sampling rate / 4
70 %! n = 128; % frequency grid size
71 %! [B0, A0] = butter(order, fc);
72 %! [H0, w] = freqz(B0, A0, n);
73 %! Nn = (randn(size(w))+j*randn(size(w)))/sqrt(2);
74 %! [Bh, Ah, Sig0] = invfreqz(H0, w, order, order);
75 %! [Hh, wh] = freqz(Bh, Ah, n);
76 %! [BLS, ALS, SigLS] = invfreqz(H0+1e-5*Nn, w, order, order, [], [], [], [], "method", "LS");
77 %! HLS = freqz(BLS, ALS, n);
78 %! [BTLS, ATLS, SigTLS] = invfreqz(H0+1e-5*Nn, w, order, order, [], [], [], [], "method", "TLS");
79 %! HTLS = freqz(BTLS, ATLS, n);
80 %! [BMLS, AMLS, SigMLS] = invfreqz(H0+1e-5*Nn, w, order, order, [], [], [], [], "method", "QR");
81 %! HMLS = freqz(BMLS, AMLS, n);
82 %! xlabel("Frequency (rad/sample)");
83 %! ylabel("Magnitude");
84 %! plot(w,[abs(H0) abs(Hh)])
85 %! legend('Original','Measured');
87 %! disp(sprintf('L2 norm of frequency response error = %f',err));