学习在MATLAB中建立能带矩阵 [英] Learning to build band matrices in MATLAB
问题描述
我正在尝试使用 spdiags
,但不知道如何做.我发现spdiags
的文档有些混乱,并且不确定我是否可以通过对blkdiag
的简单调用来构建这些矩阵.
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:
- 乐队的宽度
- 矩阵大小
例如:
band_width = 2;
matrix size = 9;
结果:
[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:
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.
以上内容适合制作相对较小的非稀疏矩阵.对于较大的矩阵,卷积可能会变得昂贵,您可能希望将结果表示为而是使用稀疏矩阵.以下是使用 SPDIAGS 的常规方法:
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);
这篇关于学习在MATLAB中建立能带矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!