# State-Space Representation – An Engineering Primer.

This is the first blog in what will probably be a series on the benefits of using state-space representation to implement discrete infinite impulse response (IIR) filters. Before I write about state-space and some of the things you can do with it, I want to give an overview of the difference equation and explain (hopefully intuitively) why they can be a poor choice for implementing a filter.

## The discrete difference equation

The discrete difference equation takes an input value, a list of previous input values and a list of previous output values and combines them linearly to produce the next output value. This is codified mathematically in the following equation which can be recognised as the sum of two convolutions:

Instead of the above, we could write the difference equation as two distinct difference equations chained together:

is the output of an all-zero filter which is used as input into an all-pole filter to produce . If we were to take the z-transforms of the two filters, we would see quite plainly that we can also swap the order of the filters as:

This time, is the output of an all-pole filter which is used as input into an all-zero filter to produce . If we set , the benefit of this representation is that the two filters share exactly the same state and so an implementation needs not have delay lines for both output and input. This formulation has the name “Direct Form II” and is a popular implementation choice.

Regardless of whether we implement the difference equation directly or use Direct Form II, the implementation is easy to realise in a C program given a set of filter coefficients… so why would we want to do anything differently?

### When difference equations go bad…

Let’s build a 6-th order elliptic filter and run the difference equation explicitly using the following GNU Octave code. The filter is designed with a passband edge frequency of 240 Hz at a 48000 Hz sample rate (which isn’t particularly low) with 6 dB of ripple in the passband and 80 dB of stopband attenuation.

N = 6; IRLen = 8000; [b, a] = ellip(N, 6, 80.0, 240.0/24000); dp_y = zeros(IRLen, 1); q = zeros(N, 1); x = 1; for i = 1:IRLen qv = x - a(2:end) * q; dp_y(i) = b * [qv; q]; q = [qv; q(1:(N-1))]; x = 0; end

And here is a plot of the impulse response and frequency response (which both look pretty good!):

Frequency Response of Double Precision Difference Equation

Oh yeah, Octave by default is using double-precision for everything. Because we like fast things, let’s specify that the states should always be stored using single precision by replacing the initialisation of q with:

q = single(zeros(N, 1));

And here is the new impulse response:

Frequency Response of Single Precision Difference Equation

Bugger! Storing the states in single precision has lead to an instability in the filter. Small errors in the state are somehow being amplified by the coefficients of the difference equation and the output is growing without bound.

I’m going to try and give some intuition here: imagine that you are trying to synthesise a low-frequency discretely-sampled sinusoid that follows a slowly decaying exponential envelope. You’ve found that there is a z-transform that does exactly what you want from a z-transform table:

You decide to implement the difference equation directly using Direct Form II leading to states that are the previous outputs of the impulse response of the all-pole component of the system.

The intuition is this: the values of the states close to are all very close to zero – but after sufficient time, will eventually reach a very high-peak relative to their starting point without any external influence. Tiny errors in these small state values could grow by multiple orders of magnitude as the state evolves. This effectively happens at every zero crossing of the signal – and that is just illustrative component of the problem.

Ideally, the energy in the states of the system would only ever decrease when regardless of the values of . Unfortunately, this almost never happens with a resonant system implemented using a difference equation. We should ask the question: can we find better states than previous outputs of the all-pole filter?

## State-space

The Direct Form II difference equations presented earlier utilising and can be mutated into some fairly gross matrix equations:

Work through these and convince yourself they are equivalent. We can rewrite this entire system giving names to the matrices as:

These matrix equations are a state-space representation. The explicitly listed matrices before it are known as a “controllable canonical form” representation (for the case when ). is the state vector and in controllable canonical form, it holds previous values of as described in the difference equations earlier.

So why would we want to do this? Who cares that we mapped a difference equation into a set of matrix equations? I’m going to list out some reasons which probably deserve their own blogs:

1. Ability to analyse system using a vast array of matrix mathematical tools.
2. Improve the numerical stability of the system.
3. Preserving physical meanings of states during discretisation.
4. Ability to design for efficient implementations.

In this blog, we’re going to look at points one and two briefly to attempt to address the problems shown earlier.

Firstly, let’s write the state equations in terms of their z-transforms so that we can build an expression that maps input to output:

Doing some rearranging and substitution enables us to eliminate :

The term in the denominator expands to the characteristic polynomial of in and if we are trying to map a z-domain transfer function to a state-space system, it needs to equal the denominator of the transfer function. Just as the poles of a transfer function are roots of the denominator, the poles of a state-space system are the eigenvalues of the matrix. The numerator of the above expression is a matrix of polynomials in showing how state-space is naturally able to handle multiple-input multiple-output (MIMO) systems.

Earlier, we asked can we pick better values for the states? Before getting to that, let’s answer a different question: can we pick different values for the states? The answer is: yes – and we can prove it trivially by substituting with where is some invertible square matrix:

This changes the coordinate system that the state vector exists in. We can pick any invertible matrix and use it to modify a system’s , and matrices keeping the system output identical. The quantity is a similarity transform on and it preserves the eigenvalues/characteristic polynomial of for all invertible .

## State-space degrees of freedom

The coefficients of a difference equation are unique for a particular impulse response. The coefficients of the state-space representation for are not. In-fact, we have already demonstrated this previously by showing we can change the coordinate system of the state-vector.

Let’s go through the process of taking a 2×2 SISO system and finding the transfer function.

We can select all of these quantities to match a given second order transfer function – but how should we choose them? What makes for good coefficients? What does good mean? We could force some values to zero or one to minimize multiplies? If we want to improve numeric performance, given that the matrix is responsible for moving states forward in time, it seems reasonable to minimize the impact that errors in the state vector can have when multiplied by – this is akin to making as well conditioned as possible. This might be a good strategy for fixing our example 6th order system.

Orthogonal matrices are well-conditioned and for those deeply familiar with IIR design, you may also know that the state update for a coupled form IIR implementation is effectively determined by an orthonormal matrix that has been attenuated by some scalar. Coupled form state-updates can only be used to mimic a conjugate pole pair, but for every classical IIR design (Butterworth, Chebyshev I/II, Cauer/Elliptic) of even order (like our example 6th order problematic system), all the poles are in conjugate pairs. Start by defining as an orthogonal matrix:

The transfer function becomes:

There are two remaining free variables we can pick. Somewhat arbitrarily, we will select and to get:

We now have a system of equations we can solve for the unknown matrix quantities that will create a state-space system that mimics a 2nd order resonant transfer function.

## Chaining systems together

Consider we have two systems which we would like to connect together:

And:

We can make direct substitutions to get:

We can re-write the above as a set of block matrix equations:

This provides a direct method for connecting systems together into one larger system. As is an upper-triangular block-diagonal matrix, the eigenvalues of the new system are the same as those of the existing systems and the term in the connected system has no influence. Given that, can we decouple the sections completely? i.e. can we completely eliminate the term by using a similarity transform as described previously? Let’s pose the question using block matrices:

There is only one valid set of solutions for these equations:

Where the final equation is a Sylvester equation which can be solved without too much pain programatically (i.e. using a matrix inverse) if and only if and share no common eigenvalues. If we do this, we end up with the following system:

This will be better conditioned and have some other benefits in terms of efficient implementations. This block-diagonalisation we just performed is the equivalent of performing the partial-fraction decomposition on the cascaded system (which I’ve never seen a nice looking algorithmic solution for).

## Bringing it home

Let’s take our problematic 6th order system, break it up into 3 second order state-space sections using the coupled-form mapping we described and evaluate the performace again:

Performance of the coupled-form state-space systems vs. the double precision difference equation

There are 4 data-sets:

1. The original double-precision difference equation results.
2. The concatenated coupled-form systems without block-diagonalisation storing the states in single precision.
3. The concatenated coupled-form systems without block-diagonalisation storing the states in a q15 format (15 bits of fractional precision).
4. The concatenated coupled-form systems with block-diagonalisation storing the states in q15 format.

The performance difference between 2 and the block-diagonalised system with states in signle precision is negligible and so is not included in the plots. The performance difference between 1, 2 and 4 is practiacally identical in the passband. There is some fudging going on with the q15 plots because the precision is fixed but the range is not. I’ve tried to make things more even by:

• 2-Norm matching the and matrices of the systems without diagonalisation.
• 2-Norm matching each sub-section of the and matrices of the system with diagonalisation (which we can do because they are all operating independetly).
• 2-Norm matching the matrices of the diagonalised and undiagonalised systems after the above has happened (which also requires modifying ).

The performance of 1, 2 and 4 are all incredibly good. The performance of 3 shows that cascading leads to error build-up that significantly compromises the output.

These coupled-form state-space filter realisations are good down to very low frequencies. I have had success synthesising sub 10 Hz 16th order elliptic filters that work just fine with single-precision floating point. Next time, we’ll look at preservation of state meanings when we discretise an analogue system.

# An attempt at an intuitive description of the QR decomposition using Householder reflectors

I really like the Householder matrix. I’ve blogged about its ability to generate an orthonormal basis containing a particular vector in a previous blog post. This blog post is a bit of a tutorial which will use the Householder matrix to perform a QR decomposition. Applying Householder reflectors to compute a QR decomposition is nothing new, but I want this blog post to attempt to provide some intuition into how the algorithm works starting from almost nothing. We’ll briefly visit inner products, matrix multiplication, the Householder matrix and then build a QR decomposition in C. I’m not going to use formal language to define these operations unless it’s necessary. I’m going to assume that you understand things like matrix multiplication and what a matrix inverse is, but not much more than that. The post will be written assuming complex numbers are being used (the C implementation will not… maybe I will add one later).

## The inner product

The inner product takes two vectors and produces a scalar. You can think of a vector as being an array of length values representing coordinates in some N-dimensional space.

Note the bar in the above indicates conjugation. If and are row vectors, we could write the above as:

Where is the transposed conjugate of . Two vectors are said to be orthogonal if they have an inner product of zero. If the inner product of a vector with itself is equal to one, the vector is said to be a unit-vector. The inner product of a vector with a unit-vector is the proportion of that vector that is pointing in the same direction as the unit-vector i.e. if is some unit vector and I define a new vector as:

The vector is now orthogonal to i.e. .

There are some good geometric visualisations of these for two and three dimensional vectors… but everything continues to work in arbitrary dimensions. The above image contains two plots which both contain two perpendicular unit vectors (red and green) and an arbitrary vector (black). In both plots we can verify the red and green vectors are unit vectors by applying the inner product. We can also verify they are orthogonal by applying the inner product. If we compute the inner product of the black vector on the two unit vectors, then multiply each of the scalar results by the corresponding unit vectors used to compute them and sum the results, we should get back the black vector.

## Matrix multiplications

We can define matrix multiplication using inner products of the vectors which make up the rows of the left-hand side matrix with the vectors which make up the columns of the right-hand side matrix.

We can use this to demonstrate that a matrix that is made up of rows (or columns) that are all orthogonal to each other is trivially invertible – particularly if the vectors are unit vectors, in which case the inverse of matrix is . To make this particularly clear:

If the rows are orthogonal to each other, the inner products off the main diagonal will all be zero. If the rows are unit vectors, the diagonal entries are by definition 1 and .

## The Householder matrix

Define a matrix as:

Where is a unit vector. Then:

Thereore is its own inverse () and must also be unitary ().

If we can work out a method to choose such that will contain a particular unit vector and we multiply by any scaled version of vector , we will get a vector which has only one non-zero entry (because all other rows of the matrix will be orthogonal to ). I have described this process before in a previous blog post but will repeat it here with some more detail. Define a vector that we want the first column of to equal:

If is real, we can break into its individual coordinates to solve for their values:

Given the way the matrix is defined, the computation of the square root is unnecessary in an implementation. This is best seen if we expand out the matrix:

Define a scalar and a vector :

Then . This is a particularly useful formulation because we rarely want to compute in its entirity and perform a matrix mutliplication. Rather, we compute:

Which is substantially more efficient. A final necessary change is necessary: if is close to one (which implies all other coefficients of are approaching zero), will begin to approach infinity. There is a relatively simple change here which is to recognise that and are parallel but pointing in different directions (their inner-product is -1). If we don’t care about the direction of the vector, we can change its sign to be the most numerically suitiable for the selection of i.e. if use otherwise use .

This is actually very useful in many applications, one of which is the QR decomposition.

## The QR decomposition

The QR decomposition breaks down a matrix into a unitary matrix and an upper-triangular matrix . There are a number of ways to do this, but we are going use the Householder matrix.

Let’s start by defining a series of unitary transformations applied to as:

Where are all n-by-n unitary matrices. Notice that the first row of will be unmodified by all the transforms that follow. The first two rows of will be unmodified by all the transforms that follow – and so-on.

If we can somehow force the first row of to be the first column of scaled to be a unit vector (while keeping unitary), the first column of will contain only one non-zero entry. We then set about finding a way to select such that the second column contains only two non-zero entries… and so on. Once the process is finished, is upper triangular and the unitary matrix which converts into this form can be written as:

And:

When we follow the above process and the matricies are chosen to be Householder matrices, we have performed the QR decomposition using Householder matrices.

Follows is the C code that implements the decomposition. Because the algorithm repeatedly applies transformations to to eventually arrive at , we will design an API that operates in-place on the supplied matrix. The orthogonal matrix will be built in parallel. The N-1 iterations over the i variable, correspond to the N-1 transformation steps presented earlier. I make no claims about the computational performance of this code. The numerical performance could be improved by using a different method to compute the length of the vector (first thing that happens in the column loop).

/* Perform the QR decomposition of the given square A matrix. * A/R is stored and written in columns i.e. * a[0] a[3] a[6] * a[1] a[4] a[7] * a[2] a[5] a[8] * * q is stored in rows i.e. * q[0] q[1] q[2] * q[3] q[4] q[5] * q[6] q[7] q[8] */ void qr(double *a_r, double *q, int N) { int i, j, k;   /* Initialise qt to be the identity matrix. */ for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { q[i*N+j] = (i == j) ? 1.0 : 0.0; } }   for (i = 0; i < N-1; i++) { double norm, invnorm, alpha; double *ccol = a_r + i*N;   /* Compute length of vector (needed to perform normalisation). */ for (norm = 0.0, j = i; j < N; j++) { norm += ccol[j] * ccol[j]; } norm = sqrt(norm);   /* Flip the sign of the normalisation coefficient to have the * effect of negating the u vector. */ if (ccol[0] > 0.0) norm = -norm; invnorm = 1.0 / norm;   /* Normalise the column * Convert the column in-place into the w vector * Compute alpha */ ccol[i] = (1.0 - ccol[i] * invnorm); for (j = i+1; j < N; j++) { ccol[j] = -ccol[j] * invnorm; } alpha = 1.0 / ccol[i];   /* Update the orthogonal matrix */ for (j = 0; j < N; j++) { double acc = 0.0; for (k = i; k < N; k++) { acc += ccol[k] * q[k+j*N]; } acc *= alpha; for (k = i; k < N; k++) { q[k+j*N] -= ccol[k] * acc; } }   /* Update the upper triangular matrix */ for (j = i+1; j < N; j++) { double acc = 0.0; for (k = i; k < N; k++) { acc += ccol[k] * a_r[k+j*N]; } acc *= alpha; for (k = i; k < N; k++) { a_r[k+j*N] -= ccol[k] * acc; } }   /* Overwrite the w vector with the column data. */ ccol[i] = norm; for (j = i+1; j < N; j++) { ccol[j] = 0.0; } } }

The algorithm follows almost everthing described on this page – albiet with some minor obfuscations (the vector is stored temporarily in the output matrix to avoid needing any extra storage). It’s worth mentioning that the first step of initialising the matrix to isn’t necessary. The initialisation could be performed explicitly in the first iteration of the loop over i – but that introduces more conditional code.