有效地将稀疏矩阵转换为单元阵列

时间:2014-03-17 03:45:04

标签: matlab sparse-matrix

我有以下形式的稀疏矩阵

让我们举一个5x10矩阵的例子

      1  2  3  4  5  6  7  8  9  10
 1    1  1  0  0  0  0  0  0  0   0
 2    0  1  0  0  0  0  0  0  0   0
 3    .............................
 4    .............................
 5    .............................

从这个稀疏矩阵中,我想创建一个形式为

的单元格数组C.
C{1} 1
C{2} = [1,2]
...........
...........
...........

我的稀疏矩阵像40000乘790000一样高维。如何在matlab中有效地完成它。我绝对可以使用循环并且效率低下。但我希望效率最高。建议?

2 个答案:

答案 0 :(得分:2)

使用find获取索引,accumarray按列对其进行分组:

[ii, jj] = find(A);
C = accumarray(jj, ii, [], @(v) {v.'});

<强>基准

%// Random sparse matrix. Code adapted from @teng's answer
sz = [4e4 79e4];
nz = 1e5; %// number of nonzeros
A = sparse(randi(sz(1),[nz 1]),randi(sz(2),[nz 1]),1,sz(1),sz(2));

tic;    
[ii, jj] = find(A);
C = accumarray(jj, ii, [], @(v) {v.'});
toc

结果:

  • nz = 1e4

    Elapsed time is 0.099657 seconds.
    
  • nz = 1e5

    Elapsed time is 0.756234 seconds.
    
  • nz = 1e6

    Elapsed time is 5.431427 seconds.
    

答案 1 :(得分:0)

让我开始派对吧...... 让我们从基础开始:

 tic;
 sz = [ 400 7900]; % hehe...
 aMat = sparse(randi(sz(1),[1000 1]),randi(sz(2),[1000 1]),1,sz(1),sz(2));
 aCell = mat2cell(aMat,ones([sz(1) 1]));
 preC = cellfun(@(x) x(x~=0), aCell,'UniformOutput',false);
 C = cellfun(@(x) find(x), preC,'UniformOutput',false);
 toc