Reputation: 3768
I'm required to sort the matrix(each row is a feature vector) in lexicographical order.
test_mat = [10 40 30 -1 ; 43 78 -5 1; 87 54 -4 -2];
But after looking at several posts, there are:
sortrows(test_mat)
sort(test_mat)
I'm not entirely sure which method is right, as I'm getting quite different results from each.
Upvotes: 1
Views: 1459
Reputation: 1593
According to Sardar Usama's comment I'm using the test matrix:
A = [10 40 30 -1;
43 78 -5 1;
87 54 -4 -2];
sort(A,dim)
sorts every vector of A
in ascending order. If dim
is 1, then every column vector, if dim
is 2 then ever row vector.
E.g.:sort(A, 2)
sorts every row of A
in ascending order. This means that every row will be considered a row vector and will be sorted in ascending order.
% ascending sorting of every row vector
sort(A,2)
ans =
-1 10 30 40
-5 1 43 78
-4 -2 54 87
% ascending sorting of every column vector
sort(A,1)
ans =
10 40 -5 -2
43 54 -4 -1
87 78 30 1
sortrows(A, col)
sorts the rows of A
in ascending order according to the column col
. The individual rows don't change, so the rows are not modified.
E.g.:sortrows(A,1)
won't change A
at all, since the first column is already in ascending order.
sortrows(A,1)
ans = 10 40 30 -1
43 78 -5 1
87 54 -4 -2
If you just use sortrows(A)
, A
will always be sorted according to the first column by default, if you use sortrows(A,1)
, it does therefore the same thing, but you could also use sortrows(A,3)
and sort according to the 3rd column. Additionally you can also use sortrows(A,[1 3])
, which sorts first based on column 1 and all rows where column 1 has the same value will be sorted according to column 3. sortrows(A,[1 2 3 4])
is of course the same as sortrows(A)
. (thats the default)
So if your rows are feature vectors, sortrows
will order your feature vectors according to one of the features/columns, but the feature vectors/rows itself will stay unchanged and sort
will also change the rows/feature vectors itself, since every row will be changed/sorted in ascending order. So I guess you want sortrows
.
If you only have numeric values, I don't see any reason for casting.
Upvotes: 4