Say
X = [1 2;
3 4];
c = [1 2]';
I would like to find some way of doing what it seems to me like X(:,c) should do. To write it as a for loop:
for i=1:n
res(i) = X(i, c(i));
end
% res = [1 4]
is there a single statement / vectorized way of doing this?
diag(X(:,c))should do the trickExplanation:
A (slightly more complicated) example will help understand.
So what’s going on here? For each element in vector
c, you’re picking one of the columns from the original matrixX: For the first column ofR, use the first column ofX. For the second column ofR, use the first column ofX(again). For the third column ofR, use the second column ofX… and so on.The effect of this is that the element you’re interested in (defined in
c) is located along the diagonal of the matrixR. Get just the diagonal usingdiag: