2

I have an indexing problem in Matlab. Let's say that I have a m-dimensional array A with m depending on the problem.

Suppose I have vector with indices

x = [i2, ..., im]

and I want to take the vector

A(:, i_2, ..., i_m)

. If m is constant in all cases, it is not that difficult. You can just say

i_j = x(j), j = 2, ..., m

. Is it possible to do this without an if-loop (so without saying 'if m == 2 then .. if m == 3 then ...' and so on )?

Thanks for the help

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Koen
  • 346
  • 1
  • 3
  • 14

1 Answers1

3

This can be easily done converting x into cell array and generating a comma-separated list from that:

A = rand(3,3,3,3,3); % example A
x = [2 1 3 2]; % example x
ind = num2cell(x);
result = A(:, ind{:});
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    thanks, that's exactly what I want :-) – Koen Nov 13 '17 at 16:52
  • 1
    A neat little trick: you can add `':'` to the cell array where ever you want. For example: `ind = [{':'} num2cell(x)]; result = A(ind{:});` – gnovice Nov 13 '17 at 17:12