I am trying to build square band matrices using blkdiag or spdiags, but can’t figure out how. I find the documentation for spdiags a bit confusing, and am not sure I can build these matrices in a simple call to blkdiag.
I would like to build a square band matrix from two parameters:
- The width of the band
- Matrix size
For example:
band_width = 2;
matrix size = 9;
Result:
[1 1 1 0 0 0 0 0 0]
[1 1 1 1 0 0 0 0 0]
[1 1 1 1 1 0 0 0 0]
[0 1 1 1 1 1 0 0 0]
[0 0 1 1 1 1 1 0 0]
[0 0 0 1 1 1 1 1 0]
[0 0 0 0 1 1 1 1 1]
[0 0 0 0 0 1 1 1 1]
[0 0 0 0 0 1 1 1 1]
[0 0 0 0 0 0 1 1 1]
A tricky one-line way to create a matrix like this is with convolution:
An identity matrix is created of the given size, then convolved in 2-D with a square matrix of ones, then converted to zeroes and ones by taking the sign.
The above is fine for making relatively small non-sparse matrices. For larger matrices the convolution may get expensive and you would probably want to represent the result as a sparse matrix instead. Here is how you can do this in a general way using SPDIAGS: