Learning to build band matrices in MATLAB

前端 未结 1 735
一向
一向 2021-01-19 05:23

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

相关标签:
1条回答
  • 2021-01-19 05:58

    A tricky one-line way to create a matrix like this is with convolution:

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

    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:

    M = spdiags(ones(matrix_size,2*band_width+1),...
                -band_width:band_width,matrix_size,matrix_size);
    
    0 讨论(0)
提交回复
热议问题