"Roel H" <r.helsen@student.tudelft.nl> wrote in message
news:jgh0rp$po9$1@newscl01ah.mathworks.com...
> Is it possible to use a matrix as subscripts for a multidimensional
> array?
> What I want is the following: I have a nD array, say 'A', and a nby1
> 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)
That's a commaseparated list.
http://www.mathworks.com/help/techdoc/matlab_prog/br2js351.html
This example is the "Function Call Arguments" example on that page, if you
think of subscripted indexing as a function call.
> I would like to get rid of the intermediate step, since it involves
> creating extra variables I don't need.
MATLAB treats indexing like:
y = A(onlyIndexArray);
as linear indexing (assuming onlyIndexArray is not a logical array; that
would be logical indexing) and retrieves the elements whose linear indices
are stored in onlyIndexArray. It does not treat the index array as a
subscript index because it has the same length as the number of dimensions
in A, as you hoped.
The approach I would use in this case is the commaseparated list approach,
though you may want to look at the implementation of the SUB2IND function
and write your own function, based on SUB2IND, that accepts a vector of
indices rather than individual vectors for the index in each dimension.
> 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
> ndimensional grid with 10 elements in each dimension)
That's correct. That's the "Function Return Values" example on the page I
linked above.

Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
