Path: news.mathworks.com!not-for-mail
From: "Doug Hull" <hull@mathworks.SPAMPROOFcom>
Newsgroups: comp.soft-sys.matlab
Subject: Re: 2D Array to Index a 3D Array?
Date: Fri, 21 Nov 2008 18:34:02 +0000 (UTC)
Organization: The MathWorks Inc
Lines: 51
Message-ID: <gg6uuq$g83$1@fred.mathworks.com>
References: <718c2ac0-bc91-4be9-8fc5-5a4fbd364596@s20g2000yqh.googlegroups.com> <gg6tr8$t1e$1@fred.mathworks.com>
Reply-To: "Doug Hull" <hull@mathworks.SPAMPROOFcom>
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 1227292442 16643 172.30.248.37 (21 Nov 2008 18:34:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 21 Nov 2008 18:34:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869436
Xref: news.mathworks.com comp.soft-sys.matlab:502371


clear
clc


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

J = [1,2; 2,1];

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

[nR, nC] = size(J);

for r = 1:nR
    for c = 1:nC
        D(r,c) = M(r,c,J(r,c));
    end
end


"Doug Hull" <hull@mathworks.SPAMPROOFcom> wrote in message <gg6tr8$t1e$1@fred.mathworks.com>...
> Chris,
> 
> There is going to have to be some kind of loop in there.  Why are you trying to avoid them.  There once was a performance reason to avoid FOR loops, but that has been largely removed by the JIT.
> 
> -Doug
> 
> Chris Maryan <kmaryan@gmail.com> wrote in message <718c2ac0-bc91-4be9-8fc5-5a4fbd364596@s20g2000yqh.googlegroups.com>...
> > 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];
> > 
> > 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,
> > 
> > Chris
> >