Indexing of unknown dimensional matrix
For the general case where J
can be any length (which I assume always matches the number of dimensions in M
), there are a couple options you have:
You can place each entry of
J
in a cell of a cell array using thenum2cell
function, then create a comma-separated list from this cell array using the colon operator:cellJ = num2cell(J); output = M(cellJ{:});
You can sidestep the
sub2ind
function and compute the linear index yourself with a little bit of math:sizeM = size(M); index = cumprod([1 sizeM(1:end-1)]) * (J(:) - [0; ones(numel(J)-1, 1)]); output = M(index);