淘先锋技术网

首页 1 2 3 4 5 6 7

SPARSE函数

S = sparse(A)   ----->   把全矩阵转换为稀疏矩阵

S = sparse(i,j,s,m,n,nzmax)   ----->   标准形式

S = sparse(i,j,s,m,n), nzmax=length(s)

S = sparse(i,j,s), m = max(i), n = max(j)

S = sparse(m,n) == sparse([],[],m,n,0)

————————————————————————————————

备注: s 通常为一维向量 如 s = ones(N,1) 或 s = ones(1,N);

若为多维向量 sparse函数也不会报错 因为s 会自动降维,这里需要注意matlab的序号排列规则;

其规则为 列优先,以二位矩阵为例如:

a(1)  a(n+1)  ... a(mn+1)

a(2)  a(n+2)  ... a(mn+2)

...    ...    ...   ...

a(n)  a(n+n)  ... a(mn+n)

i,j 规则同上,因此 sparse(i,j,s) 实际意义为 a[i,j]= s(k),s中的第k个数,位于角标i,j的位置上

例如:     e = [1 3 5; 2 4 6];                   % e为2D矩阵

D = =sparse(1:6,[2:6 1],e,6,6);       % 稀疏为6*6的矩阵

full(D)                               % 满矩阵显示

_______________________________________________

e =

1     3     5

2     4     6

D =

(6,1)        6

(1,2)        1

(2,3)        2

(3,4)        3

(4,5)        4

(5,6)        5

full(D) =

0     1     0     0     0     0

0     0     2     0     0     0

0     0     0     3     0     0

0     0     0     0     4     0

0     0     0     0     0     5

6     0     0     0     0     0

_____________________________________________________

sparse用法: 在有限差分计算中,考虑4阶差分算法,其稀疏矩阵为

以6*6矩阵为例:

ans =

0            2/3          -1/12           0            1/12         -2/3

-2/3            0            2/3          -1/12           0            1/12

1/12         -2/3            0            2/3          -1/12           0

0            1/12         -2/3            0            2/3          -1/12

-1/12           0