Effacer les filtres
Effacer les filtres

Replace the values of a matrix by another values.

2 vues (au cours des 30 derniers jours)
Eranja Noopehewa
Eranja Noopehewa le 31 Juil 2018
Modifié(e) : jonas le 31 Juil 2018
i have a 3*3 matrix like [750 360 500 ; 550 520 780 ; 150 350 270] I want to replace these values in the matrix by comparing each row from the largest to small. (i.e largest =1 ,second largest=2 and smallest =3 ). Finally is should get a matrix like [1 3 2 ;2 3 1 ;3 1 2]

Réponse acceptée

jonas
jonas le 31 Juil 2018
Modifié(e) : jonas le 31 Juil 2018
I have a feeling there is an obvious simple solution to this problem. However, you can use this for now :)
A = [750 360 500 ; 550 520 780 ; 150 350 270];
[~,ind] = maxk(A,3,2);
out = nan(size(A));
for i = 1:3
out(sub2ind(size(A),[1:length(A)]',ind(:,i))) = i;
end
out =
1 3 2
2 3 1
3 1 2
  3 commentaires
jonas
jonas le 31 Juil 2018
Okay, it's because you are using an older release of MATLAB. Replace that line by this:
[~,ind]=sort(A,2,'descend')
jonas
jonas le 31 Juil 2018
Modifié(e) : jonas le 31 Juil 2018
I'm happy it helped, but to be honest you should accept the other answer. I was going to delete this one but wanted to wait until you were finished with testing it. This one is slower and probably not as robust. It is also not generalized, and currently only works for 3x3 matrices.

Connectez-vous pour commenter.

Plus de réponses (1)

Star Strider
Star Strider le 31 Juil 2018
This appears to do what you want:
A = [750 360 500 ; 550 520 780 ; 150 350 270];
[~,Idx] = sort(A,2,'descend'); % Sort Matrix Row-Wise, Descending, Return Indices
[~,Out] = sort(Idx,2) % Sort Indices Row-Wise, Ascending, Return Indices To Get Output
Out =
1 3 2
2 3 1
3 1 2
  2 commentaires
jonas
jonas le 31 Juil 2018
+1
I figured there was a simpler solution...
Star Strider
Star Strider le 31 Juil 2018
Thank you.
This took a bit of experimenting to discover. It is probably robust, although I did not test it with other matrices.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by