MATLAB: Creating a Matrix C from Matrices A and B such that C(i,j) = A(B(i,j))

coordinatesgpumatrixParallel Computing Toolbox

Hello everyone,
My problem is the following. I have two matrices. A is of size Nx1. B is of size KxM, and is composed of integers between 1 and N. I want to create a new matrix C of size KxM, such that
C(i,j) = A(B(i,j));
One obvious way would be to loop "for i=1:K … for j=1:K" but time efficiency is critical. Idealy, I would like to run this on GPU.
That does not look like a very specific problem so my intuition is that there should a simple way to do it that I am missing.
Thanks a lot if you have an idea.

Best Answer

The optimal and simplest way on the CPU is the single command,
C=A(B)
As for working on the GPU...you might see if things speed up if you make A and B into gpuArray objects, but if A is large, I'm not sure GPU-speedup is possible.
Related Question