diag(X(:,c))
should do the trick
Explanation: An example (a little more complex) will help to understand.
>>X = [1 2; 3 4; 5 6; 7 8] X = 1 2 3 4 5 6 7 8 >> c = [1 1 2 1]; >> R = X(:,c) R = 1 1 2 1 3 3 4 3 5 5 6 5 7 7 8 7
So what is going on here? For each element in vector c
you select one of the columns from the original matrix X
: for the first column R
use the first column X
For the second column R
use the first column X
(again). For the third column R
use the second column X
... etc.
The effect of this is that the element of interest to you (defined in c
) is located on the diagonal of the matrix R
Get only the diagonal using diag
:
>>diag(R) ans = 1 3 6 7
source share