Matlab:在稀疏矩阵中有效地分配值

时间:2014-09-29 21:36:07

标签: matlab matrix

我在Matlab工作,我遇到了下一个问题: 我有Bnx2元素矩阵,其中包含用于分配大稀疏矩阵A(几乎500,000x80,000)的索引。对于B的每一行,第一列是A的列索引,必须包含1,第二列是A的列索引,必须包含-1 。 例如:

B=  1   3
    2   5
    1   5
    4   1
    5   2

对于这个B矩阵,The Corresponding A矩阵必须是这样的:

A= 1    0   -1    0    0
   0    1    0    0   -1
   1    0    0    0   -1
  -1    0    0    1    0
   0   -1    0    0    1

因此,对于i的行Bi的相应行A必须填充零,除了A(i,B(i,1))=1和{{1} }}

对于B的所有行,A(i,B(i,2))=-1循环非常容易,但它非常慢。我也尝试了下一个表述:

for

但是matlab给了我一个" Out of Memory Error"。如果有人知道更有效的方法,请告诉我。

提前致谢!

2 个答案:

答案 0 :(得分:0)

我认为您应该可以使用sub2ind函数执行此操作。此函数将矩阵下标转换为线性索引。你应该能够这样做:

pind = sub2ind(size(A),1:n,B(:,1)); % positive indices
nind = sub2ind(size(A),1:n,B(:,2)); % negative indices
A(pind) = 1;
A(nind) = -1;

编辑:我(错误地,我认为)假设稀疏矩阵A已经存在。如果它不存在,那么这种方法不是最好的选择。

答案 1 :(得分:0)

您可以使用sparse功能:

m = size(B,1); %// number of rows of A. Or choose larger if needed
n = max(B(:)); %// number of columns of A. Or choose larger if needed
s = size(B,1);
A = sparse(1:s, B(:,1), 1, m, n) + sparse(1:s, B(:,2), -1, m, n);