简体   繁体   中英

MATLAB accessing multiple elements in sparse matrix using row and column index vectors

I feel there should be an easy solution but I can't find it:

I have the sparse matrices A B with the same dimension n*n . I want to create matrix C which copies values in A where B is non-zero.

This is my approach:

[r,c,v] = find(B);

% now I'd like to create an array of values using indices r and c, 
% but this doesn't work (wrong syntax)
v2 = A(r,c);

% This won't work either
idx = find(B); % linear indexing, too high-dimensional
v2 = A(idx);

% and create C
C = sparse(r,c,v2,n,n);

Here are some more details:

  • My matrices are very large, so the solution needs to be efficient. C(B~=0) = B(B~=0); won't do it, unfortunately.
  • Linear indexing won't work either as the matrices are too large ( Matrix is too large to return linear indices. ).

Is there really no way to use 2-dimensional indices?

Thanks for your help!

I think C = A .* (B~=0); should work. Only non-zeros will be accessed in the entrywise multiplication of two sparse matrices so it will be fast.

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