构造稀疏矩阵,稀疏是做什么的?

时间:2014-06-06 06:01:59

标签: matlab sparse-matrix

让我们考虑以下矩阵

 A = [ 0   0   0   5
      0   2   0   0
      1   3   0   0
      0   0   4   0]

A =

     0     0     0     5
     0     2     0     0
     1     3     0     0
     0     0     4     0

如果我们这样做

sparse(A)

ans =

   (3,1)        1
   (2,2)        2
   (3,2)        3
   (4,3)        4
   (1,4)        5

它只显示这些元素的非零元素和索引,但是如何使用这些数据来构造新的向量或数组呢?我也想了解下面的命令

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

它的定义是

i和j分别是矩阵的非零元素的行和列索引的向量。 s是非零值的向量,其索引由相应的(i,j)对指定。 m是结果矩阵的行维度,n是列维度。

但它是否有助于我们创建新数组或一般是什么是稀疏命令的想法?我知道它是存储的优化并且只采用非零元素,但我们如何在进一步计算中使用结果?提前感谢

1 个答案:

答案 0 :(得分:3)

这只是存储问题,使用稀疏矩阵作为普通矩阵:

A = [ 0   0   0   5
      0   2   0   0
      1   3   0   0
      0   0   4   0];

B = [ 1   6   1   5
      6   2   0   0
      9   3   5   9
      8   7   4   0];


A = sparse(A); % Reduce memory footprint

C = B*A; % Continue thinking of matrix A as a normal matrix

D = A(:, 2); % Address elements as if A is normal matrix ...
             % i.e. D = [0 2 3 0].'

语法:

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

用于直接将矩阵构造为稀疏矩阵(不临时分配正常矩阵):

n = 4; % Final row count
m = 4; % Final column count
i = [3 2 3 4 1]; % Non null rows indices
j = [1 2 2 3 4]; % Non null columns indices
s = [1 2 3 4 5]; % Non null values    
AA = sparse(i, j, s, n, m) % Same matrix as 'sparse(A)' without temporary allocation of full A
相关问题