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

1 view (last 30 days)
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.

Accepted Answer

Matt J
Matt J on 20 Sep 2015
Edited: Matt J on 20 Sep 2015
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.
  1 Comment
Sylvain Catherine
Sylvain Catherine on 21 Sep 2015
Thank you Matt J for your time. It was the first thing I tried... improperly ! Now it works just fine.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!