# Demo entry 6360663

Biquad Calculator

Submitted by Jeff on May 02, 2017 at 14:34
Language: Matlab. Code size: 2.6 kB.

```function [filter] = CalcBiquad(type, Fc, Q, gain, Fs)
% CALCBIQUAD    Calculates the coefficients for a Biquad filter
%               of the selected type and user input parameters.
%
%   H = CalcBiquad(TYPE, Fc, Q, GAIN, Fs) returns a structure
%       containing the user parameters, numerator coefficients
%       and denominator coefficients.
%
%       If no sample frequency is given, Fs is assumed to be 44100.
if nargin < 5
Fs = 44100;
end

if Fc < 20 || Fc > 20000
error('Frequency value is beyond useable range. Limit frequency to the range of 20Hz - 20kHz')
end
b0=0;b1=0;b2=0;a0=0;a1=0;a2=0;

if Q > 10
error('Q is too high. Use a value below 10 or use a notch filter')
end
if Q > 10
error('Q is too low. Use a value below 10 or use a notch filter')
end

A = sqrt(10 ^ (gain/20));
w0 = 2 * pi * (Fc/Fs);

alpha = sin(w0)/(2*Q);

switch type
case {'lowPass','LowPass','lp','LP', 1}
b0 = (1 - cos(w0))/2;
b1 = 1 - cos(w0);
b2 = (1 - cos(w0))/2;
a0 = 1 + alpha;
a1 = -2*cos(w0);
a2 = 1 - alpha;
case {'highPass','HighPass','hp','HP', 2}
b0 = (1 + cos(w0))/2;
b1 = -(1 + cos(w0));
b2 = (1 + cos(w0))/2;
a0 = 1 + alpha;
a1 = -2*cos(w0);
a2 = 1 - alpha;
case {'notch','Notch', 3}
b0 = 1;
b1 = -2*cos(w0);
b2 = 1;
a0 = 1 + alpha;
a1 = -2*cos(w0);
a2 = 1 - alpha;
case {'Peak','peak','bell', 'peaking','Peaking',4}
b0 = 1 + alpha*A;
b1 = -2*cos(w0);
b2 = 1 - alpha*A;
a0 = 1 + alpha/A;
a1 = -2*cos(w0);
a2 = 1 - alpha/A;
case {'LowShelf', 'lowShelf', 'lowshelf', 'ls','LS',5}
b0 = A*( (A+1) - (A-1)*cos(w0) + 2*sqrt(A)*alpha);
b1 = 2*A*( (A-1) - (A+1)*cos(w0));
b2 = A*( (A+1) - (A-1)*cos(w0) - 2*sqrt(A)*alpha);
a0 = (A+1) + (A-1)*cos(w0) + 2*sqrt(A)*alpha;
a1 = -2*( (A-1) + (A+1)*cos(w0));
a2 = (A+1) + (A-1)*cos(w0) - 2*sqrt(A)*alpha;
case {'HighShelf', 'highShelf', 'highshelf','hs','HS', 6}
b0 = A*( (A+1) + (A-1)*cos(w0) + 2*sqrt(A)*alpha);
b1 = -2*A*( (A-1) + (A+1)*cos(w0));
b2 = A*( (A+1) + (A-1)*cos(w0) - 2*sqrt(A)*alpha);
a0 = (A+1) - (A-1)*cos(w0) + 2*sqrt(A)*alpha;
a1 = 2*( (A-1) - (A+1)*cos(w0));
a2 = (A+1) - (A-1)*cos(w0) - 2*sqrt(A)*alpha;
end

% Concatenate coefficients into single matrix
b = [b0 b1 b2];
a = [a0 a1 a2];

filter = struct('Type', type, 'Fstart', Fc, 'Gain', gain ...
, 'SampleFrequency', Fs, 'b', b, 'a', a);
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.