1

I have a list of coordinates I would like to sample from a Matrix. Is there any elegant way to do it?

Ideally, something that looks like:

A = magic(5)

A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

r = 1:5; % row coordinates
c = 5:-1:1; % column coordinates

A(r,c)

ans = 

    15 14 13 12 11

Which is equivalent to

for k=1:length(r)
    A(r(k), c(k))
end

I am sure someone has asked that, but I couldn't find it anywhere.

Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74

1 Answers1

2

Applying @excaza comment I was able to solve this with:

rc_ids = sub2ind(size(A), r,c);
A(rc_ids)
Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74