5 回答

TA貢獻1829條經驗 獲得超9個贊
a=rand(100,100); tic [b,pos]=sort(a(:,1)); aa=a(pos,:); toc tic A=sortrows(a,1); toc det(aa-A) 前面的算法時間要短,效果是一樣的 Elapsed time is 0.000110 seconds. Elapsed time is 0.000259 seconds. ans = 0 用個小矩陣檢測下 a=magic(5); tic [b,pos]=sort(a(:,1)); aa=a(pos,:) toc tic A=sortrows(a,1) toc det(aa-A) a = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 aa = 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 17 24 1 8 15 23 5 7 14 16 Elapsed time is 0.000133 seconds. A = 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 17 24 1 8 15 23 5 7 14 16 Elapsed time is 0.000223 seconds. ans = 0

TA貢獻2065條經驗 獲得超14個贊
以下是自己按照程序幫助寫的,沒有copy,希望能幫助到你。
sortrows有三種用法:
B = sortrows(A)
B = sortrows(A,column)
[B,index] = sortrows(A,...)
我們先創建一個矩陣
A=floor(gallery('uniformdata',[6 7],0)*100);
A(1:4,1)=95; A(5:6,1)=76; A(2:4,2)=7; A(3,3)=73
A =
95 45 92 41 13 1 84
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
76 61 93 81 27 46 83
76 79 91 0 19 41 1
默認依據第一列的數值按升序移動每一行,如果第一列的數值有相同的,依次往右比較。例:
B = sortrows(A)
B =
76 61 93 81 27 46 83
76 79 91 0 19 41 1
95 7 40 35 60 93 67
95 7 73 5 19 44 20
95 7 73 89 20 74 52
95 45 92 41 13 1 84
或是從某一列開始比較數值并按升序排序,例:
C = sortrows(A,2)
C =
95 7 73 89 20 74 52
95 7 73 5 19 44 20
95 7 40 35 60 93 67
95 45 92 41 13 1 84
76 61 93 81 27 46 83
76 79 91 0 19 41 1
亦可以從某一列開始以降序排列,例:
D = sortrows(A, -4)
D =
95 7 73 89 20 74 52
76 61 93 81 27 46 83
95 45 92 41 13 1 84
95 7 40 35 60 93 67
95 7 73 5 19 44 20
76 79 91 0 19 41 1
如果要求每一列都按照升序排列
E=sort(A)
如果要求每一列都按照降序排列
F=-sort(-A)

TA貢獻2012條經驗 獲得超12個贊
SORTROWS Sort rows in ascending order.
它是按照行來做排序的
C =
2 2
2 1
就會變成
C =
2 1
2 2
它是把每一行當成一個數
譬如
0.4447 0.9218 0.4057
0.6154 0.7382 0.9355
0.7919 0.1763 0.9169
如果用sortrows排的話,它會把這個看成
444792184057
615473829355
791917639169
每一行中的一列相當于數的一位, 前面的權重大
如果需要每列升序排列,直接用sort即可

TA貢獻1785條經驗 獲得超8個贊
sortrows的第二個參數可以指定按哪一列排序。
1234567 | SORTROWS(X,COL) sorts the matrix based on the columns specified in the vector COL. If an element of COL is positive, the corresponding column in X will be sorted in ascending order; if an element of COL is negative, the corresponding column in X will be sorted in descending order. For example, SORTROWS(X,[2 -3]) sorts the rows of X first in ascending order for the second column, and then by descending order for the third column. |
所以,對應的代碼是:
1 | sortrows(A, 1) |
添加回答
舉報