Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: matrix manipulation
Date: Fri, 28 Nov 2008 21:30:20 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 41
Message-ID: <ggpntc$dkh$1@fred.mathworks.com>
References: <26885583.1227906197694.JavaMail.jakarta@nitrogen.mathforum.org>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1227907820 13969 172.30.248.35 (28 Nov 2008 21:30:20 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 28 Nov 2008 21:30:20 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:503710


Ross <fed.rossi@gmail.com> wrote in message <26885583.1227906197694.JavaMail.jakarta@nitrogen.mathforum.org>...
> Hi there,
> 
> I have a question regarding matrix manipulation. I am using a 'brute force' method, but I guess there might be a straightforward way to do this that I am not aware of.
> 
> Assume you have array A, s.t. [N1 N2 N3] = size(A).
> Also, assume you have a vector p, s.t. N1 = length(p), whose entries are integers between 1 and N3.
> 
> You want to obtain a new matrix B, N1-by-N2 where the rows are selected using p.
> 
> Example:
> A = [1 2;3 4];
> A(:,:,2) = [10 20;30 40]
> p = [1 2];
> 
> B = [1 2; 30 40];
> 
> 

% Data
A = [1 2;
     3 4;
     5 6];
A(:,:,2) = [10 20;
            30 40;
            50 60]

[N1 N2 N3]=size(A);

p = [1 2 2];

% Engine 1
[I J]=ndgrid(1:N1,1:N2);
K=repmat(p(:),1,N2);
B = A(sub2ind(size(A),I,J,K))

% Engine 2
Ap=permute(A,[2 1 3]);
B=Ap(:,sub2ind([N1 N3],1:N1,p)).'

% Bruno