M.ain Content

构建稀疏矩阵

创建稀疏矩阵

马铃薯草®永远不会产生稀疏矩阵自动。相反,您必须确定矩阵是否包含足够大的零百分比,以受益于稀疏技术。

密度矩阵是非零元素的数量除以矩阵元素的总数。对于矩阵M.,这将是

nnz(m)/ prod(尺寸(m));
or
nnz(m)/ numel(m);

具有非常低密度的矩阵通常是使用稀疏格式的良好候选者。

Converting Full to Sparse

您可以使用稀疏存储将完整的矩阵转换为稀疏存储函数单个参数。

For example:

一种= [ 0 0 0 5 0 2 0 0 1 3 0 0 0 0 4 0]; S = sparse(A)
S =(3,1)1(2,2)2(3,2)3(4,3)4(1,4)5

打印的输出列出了非零元素S., together with their row and column indices. The elements are sorted by columns, reflecting the internal data structure.

您可以使用稀疏矩阵将稀疏矩阵转换为完全存储满的功能,提供矩阵顺序不是太大。例如,a = full(s)反转示例转换。

将完整矩阵转换为稀疏存储不是生成稀疏矩阵最常见的方式。如果矩阵的顺序足够小,则可以进行全存储,然后转换为稀疏存储很少提供大量节省。

直接创建稀疏矩阵

You can create a sparse matrix from a list of nonzero elements using the函数五个参数。

s =稀疏(i,j,s,m,n)

一世andj对于矩阵的非零元素,分别是行和列指数的vecors。S.一世S.a vector of nonzero values whose indices are specified by the corresponding(I,J)对。M.一世S.the row dimension of the resulting matrix, andN.是列尺寸。

矩阵S.前面的示例可以直接生成

S =稀疏([3 2 3 4 1],[11 2 3 4],[11 2 3 4 5],4,4)
S =(3,1)1(2,2)2(3,2)3(4,3)4(1,4)5

command has a number of alternate forms. The example above uses a form that sets the maximum number of nonzero elements in the matrix to长度。如果需要,您可以附加第六个参数,该参数指定更大的最大值,允许您在不重新分配稀疏矩阵的情况下添加非零元素。

矩阵representation of the second difference operator is a good example of a sparse matrix. It is a tridiagonal matrix with -2s on the diagonal and 1s on the super- and subdiagonal. There are many ways to generate it—here's one possibility.

n = 5;d =稀疏(1:n,1:n,-2 * on(1,n),n,n);e =稀疏(2:n,1:n-1,of(1,n-1),n,n);s = e + d + e'
S =(1,1)-2(2,1)1(1,2)1(2,2)-2(3,2)1(2,3)1(3,3)-2(4,3)1(3,4)1(4,4)-2(5,4)1(4,5)1(5,5)-2

现在f =完整(s)显示相应的完整矩阵。

f =完整(s)
F = -2 1 0 0 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -2 1 0 0 0 1 -2

创建稀疏矩阵from Their Diagonal Elements

创建基于对角线元素的稀疏矩阵是常用操作,因此功能Spdiags.处理这项任务。它的语法是

s = spdiags(b,d,m,n)

To create an output matrixS.of sizeM.-by-N.有元素的P.对角线:

  • B.一世S.a matrix of sizemin(m,n)-by-P.。这columns ofB.是填充对角线的值S.

  • D.是长度的矢量P.其整数元素指定了哪个对角线S.填充。

也就是说,列中的元素jofB.填充指定的对角元素jofD.

笔记

If a column ofB.比对角线更换,超微对角线取自列的下部B.并且亚对角线从列的上部取出B.

一种S.an example, consider the matrixB.and the vectorD.

B = [41 11 0 52 22 0 63 33 13 74 44 24];d = [-3 0 2];

使用这些米atrices to create a 7-by-4 sparse matrix一种

A = SPDIAGS(B,D,7,4)
A =(1,1)11(4,1)41(2,2)22(5,2)52(1,3)13(3,3)33(6,3)63(2,4)24(4,4)44(7,4)74

In its full form,一种看起来像这样:

完整(a)
ans = 11 0 13 0 0 2 24 0 0 3 3 3 0 0 0 0 63 0 0 0 0 74

Spdiags.还可以从稀疏矩阵中提取对角线元素,或用新值替换矩阵对角线元素。类型helpSpdiags.有关详细信息。

Importing Sparse Matrices

您可以从MATLAB环境外的计算导入稀疏矩阵。使用Spconvert.function in conjunction with the加载command to import text files containing lists of indices and nonzero elements. For example, consider a three-column text fileT.DAT.whose first column is a list of row indices, second column is a list of column indices, and third column is a list of nonzero values. These statements loadT.DAT.一世N.to MATLAB and convert it into a sparse matrixS.

加载T.DAT.s = spconvert(t)

保存and加载命令还可以在MAT文件中处理存储为二进制数据的稀疏矩阵。

也可以看看

|

Related Topics