Indexing matrix with index pairs without using linear indexing

3 次查看(过去 30 天)
I have a set of n row indices [r1 r2 ... rn], and n column indices [c1 c2 ... cn], and I would like to get the elements corresponding to indices (r1,c1), (r2,c2) and so on. The normal way of doing this is using linear indexing A(sub2ind(size(A),r,c)). However, I am dealing with sparse matrices of ridiculous dimensions (e.g.: [2^40, 2^10] ), meaning that I can no longer use linear indexing.
A naive alternative would be with a loop:
A = sprand(2^40,2^10, 1e-10);
r = [1 4 345 922139 2^40]';
c = [2 89 100 120 1024]';
out = zeros(length(r),1);
for i=1:length(r)
out(i) = A(r(i), c(i));
end
Are there more efficient ways of doing this?

采纳的回答

Matt J
Matt J 2020-9-30

更多回答(1 个)

AS
AS 2020-9-30
Turns out I foud the solution myself after all:
out = full(diag(A(r,c)));

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by