Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Vectorizing Specific Access to Multidimensional Array
Date: Sun, 14 Sep 2008 07:46:02 +0000 (UTC)
Organization: Boston University
Lines: 27
Message-ID: <gaiffq$ja3$1@fred.mathworks.com>
References: <gai9o3$fer$1@fred.mathworks.com> <gaic32$st9$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1221378362 19779 172.30.248.37 (14 Sep 2008 07:46:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 14 Sep 2008 07:46:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 844160
Xref: news.mathworks.com comp.soft-sys.matlab:490170



"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <gaic32$st9$1@fred.mathworks.com>...
> "First Last" <nospam@nospamplease.com> wrote in message <gai9o3$fer$1@fred.mathworks.com>...
> 
> Not sure if this is what you want. The function that you need is "sub2ind".
> 
> % Data
> M=3; N=4; L=5;
> X=ceil(10*rand(M,N,L));
> 
> [i j]=ndgrid(1:M,1:N);
> % random pick of index from  to L
> k = floor(1 + L * rand(size(i)));
> k(k>L) = L; % clip incase rand returns "1"
> 
> linind = sub2ind(size(X),i(:),j(:),k(:));
> 
> % Generate z
> z=zeros(size(X));
> z(linind)=1;
> sum(X.*z,3)
> 
> % Access X directly
> Y = X(reshape(linind,size(i)))
> 
> % Bruno

This solution is perfect. Thanks very much. You have saved my department's electricity bill and my sanity!