Clear Filters
Clear Filters

Changing order of matrix and add values

1 view (last 30 days)
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!

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!