Search code examples
matlabargument-unpacking

MATLAB: Accessing an element of a multidimensional array with a list


I have a d-dimensional array, A, and vector inds with length equal to d. I would like to access the value of A at inds.

Ideally, I'd do something like A(*inds) (borrowing the unpacking syntax from Python). I'm not sure how to do this in MATLAB.

If I do A(inds) I actually get d separate values from A, which is not what I want. What I want is for element i of inds to be the ith parameter in the function call A().


Solution

  • One solution is to create a comma-separated list out of your vector of subscripted indices inds. You can do this by converting it to a cell array using NUM2CELL, then using the {:} syntax when indexing A:

    inds = num2cell(inds);
    value = A(inds{:});