Filter löschen
Filter löschen

Changing order of matrix and add values

1 Ansicht (letzte 30 Tage)
Andrea
Andrea am 10 Nov. 2015
Kommentiert: Thorsten am 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!

Akzeptierte Antwort

Thorsten
Thorsten am 10 Nov. 2015
Bearbeitet: Thorsten am 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 Kommentare
Stephen23
Stephen23 am 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 am 10 Nov. 2015
I guessed that there's a smarter way to sort columns. Thank you, Stephen to point that out.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by