MATLAB: Use a vector as an index

indexing

I have a matrix of variable dimension and would like to access it with an index stored in a variable, something like this:
matrix = [1, 2; 3, 4; 5, 6]
idx = [3, 1]
elem = matrix(idx) % should result in access to element (3, 1) => 5
Of course, this does not work and will instead get element numbers 3 and 1 (which have values 3 and 1 in that case).
I know sub2ind, but that does not help either, since the number of dimensions is variable. Is there a built-in solution for my problem or will I have to write an access method by myself? (It's not too difficult, but a built-in solution would be preferable.)

Best Answer

You can use cell expansion to comma separated list to index your matrix. So first convert your index matrix into a cell array, then convert the cell array into a list:
c = num2cell(idx);
matrix(c{:}); %expand c into comma separated list