shuffle indexes when sorting matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
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!!
댓글 수: 0
채택된 답변
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.
추가 답변 (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!