How does indexing work when sorting a matrix?
4 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 20 Aug 2024
"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
Answers (3)
Voss
on 20 Aug 2024
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 Comment
Stephen23
on 20 Aug 2024
Mario Malic
on 20 Aug 2024
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 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!