Matrix value to store as matrix index
Afficher commentaires plus anciens
Hello All,
I have a matrix A and I would like its values to be stored as its indeces in another matrix
A = [2 2 1 1 1; 3 3 3 0 2; 5 4 5 0 3]
A =
2 2 1 1 1
3 3 3 0 2
5 4 5 0 3
% the result matrix AA should look like:
AA =
0 0 1 1 1
2 2 0 0 2
3 3 3 0 3
0 4 0 0 0
5 0 5 0 0
you see how the 2 at A11 shows up on AA21 (because 2 is the second index in the first column) and 5 shows up on the fifth row (AA51). Anyhelp would be appreciated. Thnx
Réponse acceptée
Plus de réponses (2)
Andrei Bobrov
le 6 Jan 2019
ii = (1:5)';
AA = any(ii == permute(A,[3,2,1]),3).*ii;
2 commentaires
Stephen23
le 6 Jan 2019
+1 neat idea. Requires R2016b or later.
Andrei Bobrov
le 6 Jan 2019
Thank you Stephen!
For old MATLAB ( <= R2016a)
AA = any(bsxfun(@eq,ii,permute(A,[3,2,1])),3).*ii;
Without loops, works for any version:
A = [2,2,1,1,1;3,3,3,0,2;5,4,5,0,3]
S = size(A);
C = repmat(1:S(2),S(1),1);
Z = zeros(max(A(:)),S(2));
X = A>0;
Y = sub2ind(size(Z),A(X),C(X));
Z(Y) = A(X)
Giving:
Z =
0 0 1 1 1
2 2 0 0 2
3 3 3 0 3
0 4 0 0 0
5 0 5 0 0
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!