MATLAB: How to use matrix elements as indices to access elements of another matrix

indexingmatrix

I have a 5*4 matrix 'Id'
Id = [1 2 1 1;
1 2 2 2;
3 1 3 1;
1 2 3 1;
2 2 3 3]
I have another matrix Values of size 5*4*3
Values(:,:,1) = [0 0 1 2;
2 2 1 1;
2 1 0 0;
1 1 2 1;
2 1 2 2]
Values(:,:,2) = [1 0 1 2;
2 0 2 1;
1 1 2 0;
1 0 2 1;
1 2 2 0]
Values(:,:,3) = [1 2 1 0;
2 0 2 1;
2 0 1 2;
0 0 2 1;
1 1 2 2]
I want the resultant matrix of size 5*4 to be using the value in Id as the index to pick corresponding elements from Values ie.
Result(i,j) = Values(i,j,Id(i,j))
Result = [0 0 1 2;
2 0 2 1;
2 1 1 0;
1 0 2 1;
1 2 2 2]
How do I do this without a for loop?

Best Answer

Values(:,:,1) = [0 0 1 2
2 2 1 1
2 1 0 0
1 1 2 1
2 1 2 2]
Values(:,:,2) = [1 0 1 2
2 0 2 1
1 1 2 0
1 0 2 1
1 2 2 0]
Values(:,:,3) = [1 2 1 0
2 0 2 1
2 0 1 2
0 0 2 1
1 1 2 2]
Id = [1 2 1 1
1 2 2 2
3 1 3 1
1 2 3 1
2 2 3 3]
[n,m]=size(Id)
[x,y]=ndgrid(1:n,1:m)
idl=sub2ind(size(Values),x,y,Id)
Result=Values(idl)