Info

This question is closed. Reopen it to edit or answer.

How can I index a 3D matrix using three other 3D matrices (one for each dimension)

1 view (last 30 days)
I have an n by n by n 3 dimensional matrix with values, let's call it u. I have three other 3 dimensional matrices, let's call them ux, uy, and uz (all size = size(u)), that contain the new x, y, z coordinates/indices that I want to index in u. Thus, the output should be another matrix of size(u) that holds the values of u at the specified indices.
For example, if
ux(1,1,1) = 5
uy(1,1,1) = 8
uz(1,1,1) = 9
then
output(1,1,1) = u(8,5,9)
Is there a quick and efficient way to do this? I need to run this formula 8 times in a single function that is called often. Ideally, there might be a way to vectorize the above in a single line! Could anyone provide some insight?

Answers (2)

Image Analyst
Image Analyst on 29 Oct 2013
output(i,j,k) = u(uy(i,j,k), ux(i,j,k), uz(i,j,k));
Note x = columns and is the second index, not the first. And y = rows so it's the first index, not the second.

Azzi Abdelmalek
Azzi Abdelmalek on 29 Oct 2013
Look at this example
ux=randi(4,4,4,4)
uy=randi(4,4,4,4)
uz=randi(4,4,4,4)
u=rand(4,4,4);
idx=sub2ind(size(ux),uy(:),ux(:),uz(:));
output=zeros(size(ux));
output(1:numel(ux))=u(idx)

Community Treasure Hunt

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

Start Hunting!