How does indexing work when sorting a matrix?
조회 수: 3 (최근 30일)
이전 댓글 표시
My intuition is clearly off on this and any help is appreciated.
For a vector, if you sort the vector and find the indices of the sorted vector, you can reproduce the sorted vector by indexing the original vecor using the sorted indices:
r = rand(10,1);
[rsort,indsort] = sort(r);
r(indsort) % This will equal rsort exactly
rsort - r(indsort) % this will equal zero everywhere
However, strangely, this same logic doesn't seem to work when sorting matrices:
R = rand(10,10);
[Rsort,indsort] = sort(R);
R(indsort) %This does NOT match Rsort
Rsort - R(indsort) % This does NOT equal zero everyone, only in the first column
Obviously there is something really simply going on here, but I can't figure it out. Any help is appreciated.
댓글 수: 1
Stephen23
2024년 8월 20일
"However, strangely, this same logic doesn't seem to work when sorting matrices"
Perhaps this helps understand what is going on:
R = rand(10,10);
[Rsort,indsort] = sort(R);
for k = 1:size(R,2)
X = indsort(:,k);
R(X,k) - Rsort(:,k)
end
답변 (3개)
Voss
2024년 8월 20일
For matrix R, sort(R) sorts each column and indsort are row indices.
To reproduce the sorted matrix, you can convert those row indices into linear indices. Here are a few ways to do that:
R = rand(10,10)
[Rsort,indsort] = sort(R)
[m,n] = size(R);
% one way to get the linear indices from the row indices:
idx = indsort+(0:n-1)*m
% another way:
% idx = sub2ind([m,n],indsort,repmat(1:n,m,1))
% another way:
% idx = sub2ind([m,n],indsort,(1:n)+zeros(m,1))
% with linear indexing, the sorted matrix is reproduced:
Rsort-R(idx)
댓글 수: 1
Stephen23
2024년 8월 20일
Mario Malic
2024년 8월 20일
Hi,
It is explained here - https://uk.mathworks.com/company/technical-articles/matrix-indexing-in-matlab.html find linear indexing section.
R = rand(10,10)
[Rsort,indsort] = sort(R);
indsort
So, when you do the the
Rsorted = R(indsort)
because of linear indexing
% Rsorted(1, 1) will be R(8)
% Rsorted(2, 1) will be R(5)
% Rsorted(8, 8) will be R(1)
Even though it's a matrix, you will see how to use one index to access the element in the link above.
As you see, your sort operated on columns, and it gave sorted indices for each column. You can fix this by adding the number of elements from the columns to the left which is second to last line
R = rand(10, 10);
[Rsort,indsort] = sort(R);
vec = 0 : height(R) : (height(R) * width(R) - 1);
indLinExp = indsort + vec; % care, linear expansion in MATLAB
Rsort - R(indLinExp)
댓글 수: 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!