3

How can one access a vector of elements from different columns efficiently in matlab for example:

A = [1 2 5 4
     4 6 2 5
     3 6 8 9
     2 4 5 7
     2 9 4 2]

retrieve: (1, 1) (2,2) (3,1) (4,4) (5,3)

Shai
  • 111,146
  • 38
  • 238
  • 371
Reza_va
  • 91
  • 1
  • 7

2 Answers2

3

use sub2ind:

ret = [1 1;
       2 2;
       3 1;
       4 4;
       5 3];

A( sub2ind(size(A), ret(:,1), ret(:,2)) )
Shai
  • 111,146
  • 38
  • 238
  • 371
1

sub2ind is almost definitely the way to go, but if you really need it to be fast, you might find it faster to just calculate the linear indices yourself:

A = [1 2 5 4
     4 6 2 5
     3 6 8 9
     2 4 5 7
     2 9 4 2]

ret = [1 1;
       2 2;
       3 1;
       4 4;
       5 3];

n = size(A,1)

A(ret(:,1) + (ret(:,2)-1)*n)
Dan
  • 45,079
  • 17
  • 88
  • 157