Changing order of matrix and add values

2 次查看(过去 30 天)
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!

采纳的回答

Thorsten
Thorsten 2015-11-10
编辑:Thorsten 2015-11-10
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 个评论
Stephen23
Stephen23 2015-11-10
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 2015-11-10
I guessed that there's a smarter way to sort columns. Thank you, Stephen to point that out.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by