Changing order of matrix and add values

2 ビュー (過去 30 日間)
Andrea
Andrea 2015 年 11 月 10 日
コメント済み: Thorsten 2015 年 11 月 10 日
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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by