%
% demonstration of firpm
% firpm designs a linear-phase FIR filter using the Parks-McClellan algorithm.
% This algorithm uses the Remez exchange algorithm and Chebyshev approximation
% Theory to design filters with an optimal fit between desired and actual
% frequency responses.  These are sometimes called equiripple filters.
%
clear all
close all

disp('firpm designs a linear-phase FIR filter using the Parks-McClellan algorithm.  They are designed to provide an optimal fit between desired and actual frequency responses.')
disp('press enter to continue')
pause

% length of filter
M = 100;
df = 1/M;
dt=0.01;

% corner normalized to Fs (e.g. f = -0.5 to 0.5)
N = 0.25;

% frequency vector
f = -0.5:df:0.5-df;
% time vector
t = (-(M/2):(M/2)-1)*dt;

% ideal low pass is a box car
Wk = zeros(M,1);
Wk(N*M:3*N*M-1) = 1;

figure(1)
subplot(4,1,1)
plot(f,Wk)
axis([-0.5 0.5 -0.1 1.1])
title('ideal lowpass')
xlabel('normalized f')
ylabel('Wk')

% get the weights using the IDFT
wn=fftshift(real(ifft(fftshift(Wk))));

subplot(4,1,2)
plot(t,wn)
title('ideal lowpass')
xlabel('time')
ylabel('wn')

%now define the pass and stop bands of the ideal lowpass
% allow a 0.05 transition
% note that frequency expected by firpm is [0,1] where 1 is the Nyquist
% or half the sample rate.  I.e. this is a one-sided response
% The vector a, gives the amplitude response for the frequencies in ff.
disp('define the pass and stop bands of the filter. Allow a 0.05 transition band.  Note the frequency expected by firpm is [0,1] where 1 is the Nyquist (or half sample rate)')
disp('press enter to continue')
pause

ff=[0,0.45,0.55,1];
a=[1,1,0,0];
wn2=firpm(M-1,ff,a);

subplot(4,1,3)
plot(t,wn2)
title('ideal lowpass using firpm')
xlabel('time')
ylabel('wn')

% now plot the frequency amplitude response
Wk2=fft(wn2);
subplot(4,1,4)
plot(f,fftshift(abs(Wk2)))
title('ideal lowpass frequency response using firpm')
xlabel('normalized frequency')
ylabel('Wk')
axis([-0.5 0.5 -0.1 1.1])

%orient tall
%print -dps firpmdemo.ps
