Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get different column in each row

Tags:

matrix

row

matlab

I would like to get a different column out of each row from a matrix. For example:

A = [1,2;1,4;5,2]
B = [2;2;1]

the output should yield:

out = [2;4;5]

So in short: A is the matrix and B has the indices for the colums per row. How can I do this without using a loop (if it's possible)?

like image 936
Tim Avatar asked Oct 01 '12 11:10

Tim


2 Answers

You can use sub2ind to convert (i,j) indices to linear indices in matrix A

idx = sub2ind(size(A), 1:size(A, 1), B');
A(idx)

ans =

 2     4     5

That works assuming that vector B has as many entries as there are rows in A. In the above sub2ind generates a linear index for every pair of subsequent row numbers (1:size(A, 1)) and column numbers given in B.

like image 111
angainor Avatar answered Oct 05 '22 23:10

angainor


You can do it by diag(A(:,B)) , there is however a loop, but only implicit. I don't know how to do it without any loop.

like image 38
slezadav Avatar answered Oct 05 '22 23:10

slezadav