Extracting elements from a matrix according to row number

I need to extract the elements in each column of matrix A according to row numbers given by the elements of vector X. For example, I have:
A = 9 3 4 6
2 4 5 7
4 5 6 8
X = [1 3 1 2]
And I would like the indexing function to return this:
B = [9 5 4 7]
I tried B = A(X,1:end) but got an error saying "Subscript indices must either be real positive integers or logicals". Any help on this would be greatly appreciated as I am new to Matlab and can't figure out where I'm going wrong.

 Accepted Answer

I would use the sub2ind function, to convert the subscripts to linear indices:
idx = sub2ind(size(A), X', (1:4)');
B = A(idx)
B =
9
5
4
7

2 Comments

Awesome! Thank you very much for answering so promptly.
Thank you!
As always, my pleasure!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!