Path: news.mathworks.com!not-for-mail
From: Loren Shure <loren@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: index array with variable number of dimensions
Date: Mon, 10 Nov 2008 15:32:18 -0500
Organization: The MathWorks
Lines: 28
Message-ID: <MPG.23826460bc5e63ce9898ea@news.mathworks.com>
References: <gfa3oa$ej8$1@fred.mathworks.com>
NNTP-Posting-Host: shurel.dhcp.mathworks.com
Mime-Version: 1.0
Content-Type: text/plain; charset="iso-8859-15"
Content-Transfer-Encoding: 7bit
X-Trace: fred.mathworks.com 1226349138 6221 172.31.57.200 (10 Nov 2008 20:32:18 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 10 Nov 2008 20:32:18 +0000 (UTC)
User-Agent: MicroPlanet-Gravity/2.70.2067
Xref: news.mathworks.com comp.soft-sys.matlab:500071


In article <gfa3oa$ej8$1@fred.mathworks.com>, 
grenblau@yahoo.deletethis.com says...
> I have a function where I allocate a multidimensional numeric array.  The array dimensionality depends upon arguments passed to the function.  I'd like to know if there is a way to flexibly index the array.
> 
> For example, let's say I have a time series of 100 timepoints repeated 30 times.  I want to vary two different parameters across 4 and 5 values and calculate some statistic over the repeats for each parameter combination and timepoint. 
> 
> So my data could be a big array of size 100 x 30 x 4 x 5.  And my statistic array would be an array of size 100 x 4 x 5.
> 
> That's no problem.  But what if I want to make my function flexible so that if I wanted to vary 3 parameters instead of 2 I could do it with the same code.  So let's say I have another parameter that I vary over 6 values.  Then my data array would be size 100 x 30 x 4 x 5 x 6, and my statistic array would be size 100 x 4 x 5 x 6.
> 
> My problem is that I don't see any way to do the indexing.  If I want to assign a value to the statistic array, I can do it if I know how many dimensions there are:  statisticArray(:,2,3) = mean(dataArray(:,:,2,3),2)  but if there is sometimes an extra dimension then it would have to be statisticArray(:,2,3,4)=mean(dataArray(:,:,2,3,4)).  
> 
> Is there any way to have a variable number of dimensions and, say, put the indexes I want for these into a 1D vector and then just index something like:  statisticArray(:,[2 3 4])??
> 
> (note that the last thing doesn't work, but it gives the idea of what I'd like)
> 
> Thanks much.
> 

nd = ndims(x);
index = repmat({':'},1,nd);

x(index{:}) gives you nd indexing.  Now just replace whichever dimension 
you want in the vector index and you should be all set.

-- 
Loren
http://blogs.mathworks.com/loren