M.B.
M.B.

Reputation: 110

How to pick one element from each row of a matrix given column indices for each row?

For example, if a matrix is

A = [11 22 33 11; ...
     44 55 66 34; ...
     67 45 33 22]

then from each row I want to pick

col_idx = [2 4 1]    

so that the result would be

ans = 22
      34
      67

Other questions similar to this are based on R or Python. However, I am looking for a MATLAB based answer. Any help would be appreciated.

Upvotes: 0

Views: 52

Answers (1)

HansHirse
HansHirse

Reputation: 18925

I'd use sub2ind for that:

A = [11 22 33 11; 44 55 66 34; 67 45 33 22];

col_idx = [2 4 1]
row_idx = 1:size(A, 1)

A(sub2ind(size(A), row_idx, col_idx))

Output:

col_idx =
   2   4   1

row_idx =
   1   2   3

ans =
   22   34   67

Hope that helps!

Upvotes: 1

Related Questions