Effacer les filtres
Effacer les filtres

Changing order of matrix and add values

1 vue (au cours des 30 derniers jours)
Andrea
Andrea le 10 Nov 2015
Commenté : Thorsten le 10 Nov 2015
Hello
I have a matrix ( nDestinations x nRoutes )
A = 1 0 0 1 1 1
0 2 0 2 0 2
0 0 3 0 3 3
I want to; first sort the matrix like this: (Get all positive values at the top)
A = 1 2 3 1 1 1
0 0 0 2 3 2
0 0 0 0 0 3
And last I want to add a value, and a last row with the value nDestinations +1, in this case 4
A = 1 2 3 1 1 1
4 4 4 2 3 2
4 4 4 4 4 3
4 4 4 4 4 4
Is this even possible ?
Thanks!

Réponse acceptée

Thorsten
Thorsten le 10 Nov 2015
Modifié(e) : Thorsten le 10 Nov 2015
A = [1 0 0 1 1 1
0 2 0 2 0 2
0 0 3 0 3 3];
To sort only the positive values, the zero values are set to NaN:
A(A==0) = nan;
Now sort each column:
for i=1:size(A,2), A(:,i) = sort(A(:,i)); end
Replace the NaN with zeros:
A(isnan(A)) = 0;
Add a new final row of zeros:
A(end+1, end) = 0;
Set all zeros to the maximum element in A + 1:
A(A==0) = max(A(:)) + 1;
  3 commentaires
Stephen23
Stephen23 le 10 Nov 2015
Note that sort also supports a dimension argument, which means that the third step "Now sort each column" can be performed without any loop:
>> sort(A,1)
ans =
1 2 3 1 1 1
NaN NaN NaN 2 3 2
NaN NaN NaN NaN NaN 3
Thorsten
Thorsten le 10 Nov 2015
I guessed that there's a smarter way to sort columns. Thank you, Stephen to point that out.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by