Learning how to create matrix matrices in MATLAB

I am trying to build square matrices using blkdiag or spdiags , but cannot figure out how to do this. I find the documentation for spdiags bit confusing, and I'm not sure I can build these matrices with a simple blkdiag call.

I would like to build a square matrix of two parameters:

  • The width of the line
  • Matrix size

For instance:

 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] 
+4
source share
1 answer

A complex one-line way to create such a convolution matrix:

 M = sign(conv2(eye(matrix_size),ones(band_width+1),'same')); 

the identification matrix is created from a given size, then folded into 2-D with a square matrix, then converted to zeros and ones, taking sign .

The above is great for creating relatively small, non-sparse matrices. For large matrices, convolution can become expensive, and you probably want to present the result as SPDIAGS instead :

 M = spdiags(ones(matrix_size,2*band_width+1),... -band_width:band_width,matrix_size,matrix_size); 
+6
source

All Articles