Indexing matrix with index pairs without using linear indexing

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?

Plus de réponses (1)

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

Catégories

En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by