Sort function does not return correct indices

조회 수: 4 (최근 30일)
IO
IO 2019년 11월 24일
댓글: IO 2019년 11월 24일
I am using the sort function to sort values in each row of a large matrix. The function returns the correct sorted matrix, but not always the correct indices.
The row highlighted in the screenshot below provides an example (columns 1-3 are the original matrix, columns 4-6 are the sorted matrix, and columns 7-9 are the indices). In row 870, the sorted values are in the correct order, but the indices are in the opposite order. Notice the function gives the correct answer for all other lines in this example.
What am I doing wrong?
[Usort,Uind]=sort(U,2,'descend');
Check=[U,Usort,Uind];
Sorting.png
  댓글 수: 2
dpb
dpb 2019년 11월 24일
편집: dpb 2019년 11월 24일
We can't tell w/o data what generated the table...I've never observed such a problem...
Attach the raw dataset...
Which release are you using just on the most rarest of chances that a bug somehow did get introduced?
ADDENDUM: Actually 870 is NOT wrong...see Answer. I'm guessing you're looking for sorting by decreasing absolute value, not magnitude.
IO
IO 2019년 11월 24일
편집: IO 2019년 11월 24일
It is based on simulated data. Below is the whole code that generates these outputs.
There are a few rows where the sort function generates the wrong indices (eg 870, 884).
I am using Matlab R2016b.
% Create grid of households
n=100; % number of grid points on each dimension (latitute and longitude)
v=(1:1:n)'; % temporary vector
lonh=kron(ones(n,1),v); % longitude of households
lath=kron(v,ones(n,1)); % latitude of households
clear v;
% School characteristics
m=3; % number of schools
lons=[20,40,65]'; % longitude of schools
lats=[25,50,75]'; % latitude of schools
quality=[50,80,60]; % quality of schools
capacity=[3000,4000,3000]; % capacity of schools
% Create matrix of distances
dist=zeros(n^2,m); % storage matrix for distance
for i=1:m
dist(:,i)=sqrt((lath-lats(i)).^2+(lonh-lons(i)).^2);
end
% Create matrix of utilities
alpha=1; % coefficient on quality in household utility function
rng(1);
error=evrnd(0,1,[n^2,m]); % draws of error terms in utility function of households (extreme value type one)
U=-dist+alpha*repmat(quality,[n^2,1])+error; % matrix of utilities
% Create 'truthfull' ordered lists of schools
[Usort,Uind]=sort(U,2,'descend'); % ordered lists of schools for each household
Check=[U,Usort,Uind];

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2019년 11월 24일
편집: dpb 2019년 11월 24일
870 is not wrong... -7.2 (1) < -6.2 (3)
neither is 884.
884 -15.89 18.31 -10.21 18.31 -10.21 -15.89 2 3 1
-15.89 (1) < -10.21 (3) < 18.31 (2)
Maybe you're thinking in terms of abs() magnitude, not values?
  댓글 수: 1
IO
IO 2019년 11월 24일
Got it. Thanks a lot, and sorry for the trouble!

댓글을 달려면 로그인하십시오.

추가 답변 (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