简体   繁体   中英

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). 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. 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:

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

This is very easy with a for loop over all the rows of B, but it's extremely slow. I also tried the next formulation:

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

But matlab gave me an "Out of Memory Error". 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. 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. If it doesn't exist, then this method wouldn't be the best option.

You can use the sparse function:

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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