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

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?

 Risposta accettata

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)

Più risposte (1)

>> S = size(Values);
>> [R,C] = ndgrid(1:S(1),1:S(2));
>> X = sub2ind(S,R,C,Id);
>> out = Values(X)
out =
0 0 1 2
2 0 2 1
2 1 1 0
1 0 2 1
1 2 2 2

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by