From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: multi-dimensional indexing
Date: Fri, 3 Feb 2012 16:09:29 +0000 (UTC)
Organization: Technische Universiteit Delft
Lines: 18
Message-ID: <jgh0rp$po9$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1328285369 26377 (3 Feb 2012 16:09:29 GMT)
NNTP-Posting-Date: Fri, 3 Feb 2012 16:09:29 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2295120
Xref: comp.soft-sys.matlab:756653

Is it possible to use a matrix as subscripts for a multi-dimensional array?
What I want is the following: I have a n-D array, say 'A', and a n-by-1 vector, say 'ind', containing the subscripts for each dimension. I want to be able to use A(ind) and get as output A(ind(1),ind(2),...,ind(n)). Is there an elegant way to do this? (preferably without knowing n in advance)

The best I've come with so far, is the following:
temp = num2cell(ind); %convert the vector to a cell
A(temp{:})  %this command somehow gives the contents of each cell as subscripts.
(this seems to be undocumented matlab behavior, but it is pretty neat though)

I would like to get rid of the intermediate step, since it involves creating extra variables I don't need.

Thanks in advance!

Kind regards,
Roel Helsen

(by the way, the same trick can be used to group multiple outputs of functions. i.e.
temp = cell(n,1);  [temp{:}] = ndgrid(1:10); %this creates an n-dimensional grid with 10 elements in each dimension)