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:

  1. You can place each entry of J in a cell of a cell array using the num2cell function, then create a comma-separated list from this cell array using the colon operator:

    cellJ = num2cell(J);
    output = M(cellJ{:});
    
  2. 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);