'advanced' indexing question in matlab

61 Views Asked by At

I have an indexing problem in Matlab. Let's say that I have a array $A$ with $m$-dimensions with $m$ depending on the problem. So $A \in \mathbb{R}^{n_1 \times ... \times n_m}$

Suppose I have vector with indices $x = [i_2, ..., i_m]$ 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), \forall 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

2

There are 2 best solutions below

0
On BEST ANSWER

I suggest the following:

% I assume you have an m dimensional A matrix, i.e. length(size(A)) == m,
% and an index vector i of size m-1
icell = num2cell(i);   % Tranform vector to cell
out = A(:, icell{:});  % It's very simple :)
6
On

Albeit the code looks gruesome, you can construct the expression as a string and then use eval:

str = ['A(:'];
for i = 2:m
  str = [str ', ' int2str(x(i-1))];
end
str = [str ')'];
v = eval(str); %gives the desired vector