Could anyone help me how to display the top three highest values in each column and display the other values to be zero.

1 Ansicht (letzte 30 Tage)
I am having a matrix
A= [2.3433 2.8950 2.9967 3.8753 3.9190 3.9104 3.9563 3.9525;
0.5167 0.4839 0.4885 0.1197 0.2249 0.2497 0.2874 0.2798;
0.4429 0.4348 0.4009 0.2255 0.1793 0.2188 0.1807 0.1816;
0.3900 0.1836 0.1741 0.1292 0.1241 0.1093 0.1058 0.1280;
0.0792 0.1701 0.1765 0.1033 0.0859 0.0758 0.0681 0.0769;
0.2301 0.1068 0.1036 0.0698 0.0868 0.0945 0.0912 0.0847]
I want to display the top three highest values in each column and the rest of the other values should be displayed as zero.
Could anyone please help me on this.

Akzeptierte Antwort

Guillaume
Guillaume am 2 Jun. 2019
Getting the top 3 values of each column is trivial with maxk
top3 = maxk(A, 3, 1)
I don't see the point in having 0s below these values but if that's you really want, you can simply concatenate a zero matrix below that
top3padded = [mask(A, 3, 1); zeros(size(A, 1)-3, size(A, 2))]
  2 Kommentare
jaah navi
jaah navi am 2 Jun. 2019
When i use the above command its staing undefined function or variable maxk,mask.
For your info if
A=[0.5238 0.9547 0.7060 0.3709 0.9102 0.9044 0.1877 0.2748;
0.2649 0.4306 0.6451 0.8909 0.9091 0.0332 0.3219 0.2415;
0.0684 0.9616 0.5523 0.8564 0.5916 0.5324 0.4039 0.2431;
0.4363 0.7624 0.2181 0.4024 0.3326 0.7165 0.5486 0.1542;
0.1739 0.0073 0.7724 0.3180 0.8531 0.1793 0.0487 0.9564;
0.0261 0.6800 0.2280 0.6086 0.4424 0.3365 0.5527 0.9357]
i need to have
B=[0.5238 0.9547 0.7060 0 0.9102 0.9044 0 0.2748;
0.2649 0 0.6451 0.8909 0.9091 0 0 0 ;
0 0.9616 0 0.8564 0 0.5324 0.4039 0 ;
0.4363 0.7624 0 0 0 0.7165 0.5486 0 ;
0 0 0.7724 0 0.8531 0 0 0.9564;
0 0 0 0.6086 0 0 0.5527 0.9357]
Could you please help me on this.
Guillaume
Guillaume am 2 Jun. 2019
Bearbeitet: Guillaume am 2 Jun. 2019
You're probably on a version earlier than 2017b. Please fill the release field on the top right of the page.
On old versions, you'll have to use sort as shown by Geoff.
edit: Actually looking at your desired output, it's slightly more complicated:
[~, roworder] = sort(A, 1, 'descend');
A(sub2ind(size(A), roworder(4:end, :), repmat(1:size(A, 2), size(A, 1)-3, 1))) = 0

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Geoff Hayes
Geoff Hayes am 2 Jun. 2019
jaah - try using sort to sort the columns of your matrix in descending order
B = sort(A, 'descend');
To set all but the first three columns to zero, then do
B(4:end,:) = 0;

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by