Home > database >  Getting the matrix value given a vector of indices along each axis
Getting the matrix value given a vector of indices along each axis

Time:04-02

I have a Matlab matrix M with size: [70 5 3 2 10 9 5 3 21]; I have a vector with a coordinates that I want to read of that matrix: [5, 1, 1, 2, 3, 4, 1, 2, 1];

MWE example of what I am trying to get:

M = rand(70     5     3     2    10     9     5     3    21);
coordinates =  [5, 1, 1, 2, 3, 4, 1, 2, 1];

% Output desired:
M(5, 1, 1, 2, 3, 4, 1, 2, 1)

%Current attempt:
M(coordinates) 

Clearly M(coordinates) <> M(5, 1, 1, 2, 3, 4, 1, 2, 1). Is there a way of doing this?

CodePudding user response:

It's a bit awkward, but you can convert the array to a cell array, and then to a comma-separated list:

M = rand(70     5     3     2    10     9     5     3    21);
coordinates =  [5, 1, 1, 2, 3, 4, 1, 2, 1];

coords_cell = num2cell(coordinates);
result = M(coords_cell{:});
  • Related