Path: news.mathworks.com!newsfeed-00.mathworks.com!newsfeed2.dallas1.level3.net!news.level3.com!postnews.google.com!news2.google.com!npeer02.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!post01.iad.highwinds-media.com!newsfe01.iad.POSTED!7564ea0f!not-for-mail
From: Walter Roberson <roberson@hushmail.com>
Organization: Canada Eat The Cookie Foundation
User-Agent: Thunderbird 2.0.0.18 (Windows/20081105)
MIME-Version: 1.0
Newsgroups: comp.soft-sys.matlab
Subject: Re: 2D Array to Index a 3D Array?
References: <718c2ac0-bc91-4be9-8fc5-5a4fbd364596@s20g2000yqh.googlegroups.com>
In-Reply-To: <718c2ac0-bc91-4be9-8fc5-5a4fbd364596@s20g2000yqh.googlegroups.com>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
Lines: 31
Message-ID: <1oDVk.23497$9Z6.2867@newsfe01.iad>
NNTP-Posting-Host: 24.79.146.116
X-Complaints-To: internet.abuse@sjrb.ca
X-Trace: newsfe01.iad 1227293309 24.79.146.116 (Fri, 21 Nov 2008 18:48:29 UTC)
NNTP-Posting-Date: Fri, 21 Nov 2008 18:48:29 UTC
Date: Fri, 21 Nov 2008 12:48:47 -0600
Xref: news.mathworks.com comp.soft-sys.matlab:502377


Chris Maryan wrote:
> Lets say I have a 3D array M (i.e. M(x,y,z))
 
> I also have a 2D array J(x,y), where each element contains the z index
> of interest in M. Can I use J to index into M without looping (i.e.
> with a matlab indexing trick of some sort)?

> i.e.
> M(:,:,1) = [1,2;3,4];
> M(:,:,1) = [21,22;23,24];

I will presume that that should have been M(:,:,2) = <etc>

> J = [1,2; 2,1];
 
> D = M(:,:,J) % This doens't work, I'm looking for something that does
> ans = [1  22
>          23  4]
 
> Any ideas? Thanks,

D = reshape(M((1:size(M,1)*size(M,2)).' + (J(:)-1)*size(M,1)*(size(M,2))),size(J))

This can be written more clearly by introducing a temporary variable.


-- 
.signature note: I am now avoiding replying to unclear or ambiguous postings.
Please review questions before posting them. Be specific. Use examples of what you mean,
of what you don't mean. Specify boundary conditions, and data classes and value
relationships -- what if we scrambled your data or used -Inf, NaN, or complex(rand,rand)?