## 访问稀疏矩阵

### 非零元素

```load west0479 whos```
``` Name Size Bytes Class Attributes west0479 479x479 34032 double sparse ```

`nnz(west0479)`
```ans = 1887```
```format short e west0479```
```west0479 = (25,1) 1.0000e+00 (31,1) -3.7648e-02 (87,1) -3.4424e-01 (26,2) 1.0000e+00 (31,2) -2.4523e-02 (88,2) -3.7371e-01 (27,3) 1.0000e+00 (31,3) -3.6613e-02 (89,3) -8.3694e-01 (28,4) 1.3000e+02 . . .```
`nonzeros(west0479)`
```ans = 1.0000e+00 -3.7648e-02 -3.4424e-01 1.0000e+00 -2.4523e-02 -3.7371e-01 1.0000e+00 -3.6613e-02 -8.3694e-01 1.3000e+02 . . .```

### 索引和值

`[i,j,s] = find(S);`

`find` 返回向量 `i` 中的非零值的行索引、向量 `j` 中的列索引以及向量 `s` 中的自身非零值。下面的示例使用 `find` 查找稀疏矩阵中的非零索引和值。`sparse` 函数同时使用 `find` 输出和矩阵大小重新创建矩阵。

```S1 = west0479; [i,j,s] = find(S1); [m,n] = size(S1); S2 = sparse(i,j,s,m,n);```

### 稀疏矩阵运算中的索引

```B = speye(4); [i,j,s] = find(B); [i,j,s]```
```ans = 1 1 1 2 2 1 3 3 1 4 4 1```
```B(3,1) = 42; [i,j,s] = find(B); [i,j,s]```
```ans = 1 1 1 3 1 42 2 2 1 3 3 1 4 4 1```

```S = spalloc(2^30,2^30,2); S(end) = 1```
`Maximum variable size allowed by the program is exceeded.`

`S(2^30,2^30) = 1`
```S = (1073741824,1073741824) 1```

```n = 10000; A = 4*speye(n);```

```tic A(1:n-1,n) = -1; A(n,1:n-1) = -1; toc```
`Elapsed time is 0.003344 seconds.`
```tic for k = 1:n-1 C(k,n) = -1; C(n,k) = -1; end toc```
`Elapsed time is 0.448069 seconds.`

```S1 = spalloc(1000,1000,100000); tic; for n = 1:100000 i = ceil(1000*rand(1,1)); j = ceil(1000*rand(1,1)); S1(i,j) = rand(1,1); end toc```
`Elapsed time is 2.577527 seconds.`

```i = ceil(1000*rand(100000,1)); j = ceil(1000*rand(100000,1)); v = zeros(size(i)); for n = 1:100000 v(n) = rand(1,1); end tic; S2 = sparse(i,j,v,1000,1000); toc```
`Elapsed time is 0.017676 seconds.`

`$\text{C}\text{\hspace{0.17em}}\text{\hspace{0.17em}}\text{\hspace{0.17em}}\text{=}\text{\hspace{0.17em}}\text{\hspace{0.17em}}\left(\begin{array}{cccc}4& 0& 0& \begin{array}{cc}0& -1\end{array}\\ 0& 4& 0& \begin{array}{cc}0& -1\end{array}\\ 0& 0& 4& \begin{array}{cc}0& -1\end{array}\\ \begin{array}{c}0\\ 1\end{array}& \begin{array}{c}0\\ 1\end{array}& \begin{array}{c}0\\ 1\end{array}& \begin{array}{cc}\begin{array}{c}4\\ 1\end{array}& \begin{array}{c}-1\\ 4\end{array}\end{array}\end{array}\right)$`

```i = [1 5 2 5 3 5 4 5 1 2 3 4 5]'; j = [1 1 2 2 3 3 4 4 5 5 5 5 5]'; s = [4 1 4 1 4 1 4 1 -1 -1 -1 -1 4]'; C = sparse(i,j,s)```
```C = (1,1) 4 (5,1) 1 (2,2) 4 (5,2) 1 (3,3) 4 (5,3) 1 (4,4) 4 (5,4) 1 (1,5) -1 (2,5) -1 (3,5) -1 (4,5) -1 (5,5) 4```

### 可视化稀疏矩阵

`load west0479`

`spy(west0479)`