I would like to be able to extract a vector 'y' from an n-by-n matrix 'A', taking one element from each column of A, with the vector 'x' specifying the elements to be extracted. More specifically, I want to extract y(i)= A(x(i), i) for i= 1, 2, …, without using a loop. Currently, the only mechanism that I know of for doing this is the following:
A= magic(5);x= [3 3 3 4 1]; y= diag(A(x,1:5))
The disadvantage of the above is that the full matrix corresponding to the outer product of x and 1:n is generated as an intermediate result. In the above example this is not a concern, but in large scale problems this is very inefficient. I would like to know if there is a better way to go about this.
Best Answer