shuffle indexes when sorting matrix

조회 수: 1 (최근 30일)
martina testori
martina testori 2020년 9월 25일
댓글: martina testori 2020년 9월 25일
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
the cyclist 2020년 9월 25일
편집: the cyclist 2020년 9월 25일
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
martina testori
martina testori 2020년 9월 25일
Thank you very much for the hint, that makes a lot of sense!

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

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