简体   繁体   English

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

[英]Matlab:Efficient assignment of values in a sparse matrix

I'm working in Matlab and I have the next problem: I have a B matrix of nx2 elements, which contains indexes for the assignment of a big sparse matrix A (almost 500,000x80,000). 我正在Matlab中工作,我遇到了下一个问题:我有一个nx2元素的B矩阵,其中包含用于分配大型稀疏矩阵A (将近500,000x80,000)的索引。 For each row of B , the first column is the column index of A that has to contain a 1, and the second column is the column index of A that has to contain -1. 对于B每一行,第一列是A的列索引,必须包含1,而第二列是A的列索引,必须包含-1。 For example: 例如:

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

For this B matrix, The Corresponding A matrix has to be like this: 对于此B矩阵,对应的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

So, for the row i of B , the corresponding row i of A must be full of zeros except on A(i,B(i,1))=1 and A(i,B(i,2))=-1 因此,对于行iB ,相应的行iA必须满零除外A(i,B(i,1))=1A(i,B(i,2))=-1

This is very easy with a for loop over all the rows of B, but it's extremely slow. 通过在B的所有行上使用for循环,这非常容易,但是它非常慢。 I also tried the next formulation: 我还尝试了下一个公式:

A(:,B(:,1))=1
A(:,B(:,2))=-1

But matlab gave me an "Out of Memory Error". 但是matlab给我一个“内存不足错误”。 If anybody knows a more efficient way to achieve this, please let me know. 如果有人知道实现此目标的更有效方法,请告诉我。

Thanks in advance! 提前致谢!

I think you should be able to do this using the sub2ind function. 我认为您应该能够使用sub2ind函数执行此操作。 This function converts matrix subscripts to linear indices. 此函数将矩阵下标转换为线性索引。 You should be able to do it like so: 您应该可以这样做:

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;

EDIT: I (wrongly, I think) assumed the sparse matrix A already existed. 编辑:我(错误地,我认为)假定稀疏矩阵A已经存在。 If it doesn't exist, then this method wouldn't be the best option. 如果不存在,则此方法不是最佳选择。

You can use the sparse function: 您可以使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM