MATLAB: Indexing an array with a vector

indexingMATLABmatrix arrayvector

I would like to index an N-dimensional array with a vector of length N. In particular, for the 2-dimensional case I am currently doing the following.
A = rand(10);
v = randi(10,1,2);
v = num2cell(v);
A(v{:})
However, this approach seems horribly inefficient. Is there not a smarter way to convert the vector v to a proper index (comma-separated) for the array A?
Edit Let's say v = randi(10,1,2) = [ 3 5 ]. In that case, I want to obtain A(3,5).

Best Answer

%setup
As = size(A);
Aoff = cumprod([1 As(1:end-1)]);
%calculation at run-time
vidx = (v-1) * Aoff.' + 1;
A(vidx)
This will work when v is an M x N array of indices, producing a column array of M values. If your array has trailing singular dimensions being indexed then the code will not work as-is (the last entry of Aoff needs to be duplicated for all trailing singular dimensions.)
The calculation here converts the index components into linear indices using some trivial matrix multiplication.