在matlab中设置稀疏矩阵的最快方法

Mik*_*kin 3 arrays matlab matrix sparse-array sparse-matrix

我正在使用迭代方法,因此使用大型稀疏矩阵.例如,我想设置一个这样的矩阵:

1   1   0   0   1   0   0   0   0   0
1   1   1   0   0   1   0   0   0   0
0   1   1   1   0   0   1   0   0   0
0   0   1   1   1   0   0   1   0   0
1   0   0   1   1   1   0   0   1   0
0   1   0   0   1   1   1   0   0   1
Run Code Online (Sandbox Code Playgroud)

因此,只有某些对角线不为零.在我的编程中,我将使用更大的矩阵大小,但是Idea是相同的:只有少数对角线非零,所有其他条目都是零.

我知道,如何在for循环中做到这一点,但如果矩阵大小很大,它似乎没有效果.我也使用对称矩阵.如果您为我的样本矩阵和描述提供代码,我将不胜感激.

Lui*_*ndo 5

你想要spdiags:

m = 6;                       %// number of rows
n = 10;                      %// number of columns
diags = [-4 -1 0 1 4];       %// diagonals to be filled
A = spdiags(ones(min(m,n), numel(diags)), diags, m, n);
Run Code Online (Sandbox Code Playgroud)

这给出了:

>> full(A)
ans =
     1     1     0     0     1     0     0     0     0     0
     1     1     1     0     0     1     0     0     0     0
     0     1     1     1     0     0     1     0     0     0
     0     0     1     1     1     0     0     1     0     0
     1     0     0     1     1     1     0     0     1     0
     0     1     0     0     1     1     1     0     0     1
Run Code Online (Sandbox Code Playgroud)