Sort and Compare elements in a row matrix to form a new one

1 回表示 (過去 30 日間)
Konstantinos
Konstantinos 2015 年 2 月 6 日
コメント済み: Konstantinos 2015 年 2 月 6 日
I have the following row matrix (1x8):
Α = [ 1 0 0 1 0.5 0.4 0.5 0.4 ]
and I want to create a new matrix Β which contains the 5 elements of A with the higher values in a descending order:
Β = [ 1 1 0.5 0.5 0.4 ]
In the current example, A(6)=A(8)=0.4, so in this case I want to randomly choose which of these 2 elements will continue to form B and not neccesary take the one with the smaller index number (i.e A(6) instead of A(8)). If we assume that we don't know the elements of matrix A then we have to sort them and compare them before we form B. Can anyone share with me the appropriate code ?
Any help could be useful. Thanks in advance!

採用された回答

Guillaume
Guillaume 2015 年 2 月 6 日
I don't understand that bit: A(6)=A(8)=0.4, so in this case I want to randomly choose which of these 2 elements will continue to form B. Since they are the same value, chosing one at random or not does not matter, you always get the same value.
A = [1 0 0 1 0.5 0.4 0.5 0.4];
B = sort(A, 'descend');
B = B(1:5)
  6 件のコメント
Guillaume
Guillaume 2015 年 2 月 6 日
Here is one way:
A = [1 0 0 1 0.5 0.4 0.5 0.4 0.3 0.4 0.2 0.4];
[B, idx] = sort(A, 'descend'); %sort in descending order as normal
lastindices = idx(B == B(5)); %get indices for element equals to B(5)
idx(B == B(5)) = lastindices(randperm(numel(lastindices))); %and shuffle randomly
B = B(1:5)
idx = idx(1:5)
Konstantinos
Konstantinos 2015 年 2 月 6 日
Thanks a lot for the help Guillaume !

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by