我在Matlab工作,我遇到了下一个问题:
我有B
个nx2
元素矩阵,其中包含用于分配大稀疏矩阵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
的行B
,i
的相应行A
必须填充零,除了A(i,B(i,1))=1
和{{1} }}
对于B的所有行,A(i,B(i,2))=-1
循环非常容易,但它非常慢。我也尝试了下一个表述:
for
但是matlab给了我一个" Out of Memory Error"。如果有人知道更有效的方法,请告诉我。
提前致谢!
答案 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);