MATLAB: Vector indexes matrix columns

indexingMATLAB

Let M and N be natural numbers. Suppose X is an NxM matrix and y is an Nx1 vector. I want to do
for i=1:N
Z(i) = X(i, y(i));
end
without a for loop. How?

Best Answer

You can easily calculate the linear indices.
X = [1,2,3,4;5,6,7,8;9,10,11,12];
Y = [3;2;4];
% Using linear indexing:
A = X((1:size(X,1))+(Y.'-1)*size(X,1));
% Your loop:
for k = 1:numel(Y)
Z(k) = X(k, Y(k));
end
And the outputs are identical:
>> Z
Z =
3 6 12
>> A
A =
3 6 12