# shuffle indexes when sorting matrix

2 views (last 30 days)
martina testori on 25 Sep 2020
Commented: martina testori on 25 Sep 2020
Hi everyone,
I am in urgent need for a solution as I am really stuck!
I have a matrix "image" that needs to be sorted per column and I did that by:
[~, index_sorted] = sort(image,2,'descend');
which works fine and I have the indexes of the elements sorted.
However, image contains a lot of repeated values and when I order the indexes I always obtain the values in order.
So for example, if image is:
image = [0 0 0 -1; 0 0 -1 0; 1 1 0 0; 0 2 0 0]
index_sorted = [1 2 3 4; 1 2 4 3; 1 2 3 4; 2 1 3 4]
I am looking for a way to shuffle the order of those elements that have the same value in image, so that I do not always obtain the indexes in a crescendum but they are mixed, so for example in this case:
index_sorted = [2 1 3 4; 4 1 2 3; 2 1 3 4; 2 3 1 4]
or something like that.
Do you know a way to do it? Note that image is a large matrix and its elements can vary in R, as well as it can have as many repeated values as possible.
Thank you so so much for your help!!

the cyclist on 25 Sep 2020
Edited: the cyclist on 25 Sep 2020
One way that springs to mind is to add a small, random "jitter" to the values in the image. The jitter magnitude should be small enough that it never exceeds the difference between your non-equal elements. Then, for the equal elements, they will end up being sorted in a random order. For example, in your example:
jitter = 0.01 * rand(size(image));
[~, index_sorted] = sort(image+jitter,2,'descend');
Rather than manually selecting the jitter magnitude (as I chose 0.01 here), you could also select it programmatically by finding the smallest non-zero difference between elements in the same row.

#### 1 Comment

martina testori on 25 Sep 2020
Thank you very much for the hint, that makes a lot of sense!

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!