|
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
|