How to use matrix elements as indices to access elements of another matrix
Mostra commenti meno recenti
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
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
Scopri di più su Matrices and Arrays in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!