Indexing matrix with index pairs without using linear indexing

3 Ansichten (letzte 30 Tage)
AS
AS am 30 Sep. 2020
Kommentiert: Matt J am 30 Sep. 2020
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?

Akzeptierte Antwort

Matt J
Matt J am 30 Sep. 2020

Weitere Antworten (1)

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

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by