sortrows descend not working
조회 수: 6 (최근 30일)
이전 댓글 표시
Hello,
I have a matrix created in Matlab and I want to sort its rows in descending order, keeping the rows unchanged. Specifically, I want to sort rows according to value in the first column in descending order; if two rows have the same values in the first column, I want to sort the rows in descending order according to the value in the second column; and so on.
My matrix's name is "up2" and I am using the code "up2=sortrows(up2,'descend');" to obtain the sorted matrix. However, as the figure below shows sorting is not working. The figure is showing the sorted matrix after I run the code. The first four columns of rows 6 and 7 have the same values, so accroding to the values in column five row 6 should be below row 7, but it is not.
Can you please help to fix the problem? Thanks!
By the way, if it is related, col4=1-col5+col10 and col10=1-col8+col1.*log(col6+col9). When I copy the values of the first four columns here, the two rows seem to have exactly the same values:
col1 col2 col3 col4
1.20000000000000 0.100000000000000 0.200000000000000 0.832227738422948
1.20000000000000 0.100000000000000 0.200000000000000 0.832227738422948

댓글 수: 2
Stephen23
2021년 2월 4일
"The first four columns of rows 6 and 7 have the same values..."
My guess is that they don't have the same values. Lets check properly, show us the output of this command:
up2(7,:) - up2(6,:)
채택된 답변
the cyclist
2021년 2월 4일
My best guess is that the first four values are not exactly the same but differ by an amount around the floating point precision. What does
up2(7,1:4) - up2(6,1:4)
give?
(If you could upload the variable here, in a MAT file, that would be helpful for investigating.)
댓글 수: 3
the cyclist
2021년 2월 4일
편집: the cyclist
2021년 2월 4일
(I hadn't seen @Stephen Cobeldick's comment when I posted my answer. I'm guessing we posted at nearly the same time.)
The values in up2(7,4) and up2(6,4) are different (as stored in memory). The problem is that some ways of displaying that difference are not precise enough to show it. Take a look at this code:
% Define a vector where one element is very tiny compared to the other
x = [1 2e-17];
% Display this vector with the default format. (Tiny value gets rounded to zero.)
format
x
% Display both elements, in longer format. (There's still not enough precision.)
format long
x
% Display *only* the tiny value, in default format. (Greater precision is displayed.)
format
x(2)
% Explicitly force display with more precision
sprintf('%22.18f',x)
As in your vector, the tiny difference was obscured because of the display, but it was there.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!