Fill array with elements located at specified subscripts in another array

1 view (last 30 days)
I have a 3D array, A, of size IxJxK as well as a list of N 2D coordinates in an array I (see below). I want to fill a 2D array, B, of size KxN with the elements of A as indicated in the comments in the code below.
Asize = [128,128,64];
A = rand(Asize(1),Asize(2),Asize(3));
N = 1e+3;
[Ir,Ic] = ind2sub(Asize,randperm(prod(Asize(1:2)),N));
I = [Ir',Ic'];
B = zeros(Asize(3),N);
% B(:,n) should contain the elements A(I(n,1),I(n,2),:)
Is there a fast way to do this that does not involve loops?

Accepted Answer

Matt J
Matt J on 17 Feb 2017
Ap=reshape( permute(A,[3,1,2]) , Asize(3),[] );
B=Ap(:, randperm(prod(Asize(1:2)),N) ).' ;

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!