Sort Function Help and Selecting Highest Values

Hello, I am trying to create a MatLab function that takes in two inputs, x and y, and outputs select. select should be the same size as x. The elements of select should be the same as the corresponding element x if that element is one of the y largest values in x and 0 otherwise.
I know I am supposed to be using the Sort function to help pick the highest values, but I'm pretty unsure how to make this function.
Thank you for any help you can give.

回答 (1 件)

Walter Roberson
Walter Roberson 2011 年 9 月 23 日

0 投票

xsorted = sort(x(:));
y_largest_x = xsorted(end-y+1:end);
(Yes, that was deliberately written a bit clumsy.)

12 件のコメント

Kyle
Kyle 2011 年 9 月 23 日
I'm confused about the end inside of xsorted. What is that for?
Also, how do I make my out select have the corresponding highest value?
Kyle
Kyle 2011 年 9 月 23 日
Ok, so I think it got it to kind of work. when I do nHighest([1 2 44 55 3 6],3) in the command line I should get 0 0 44 55 0 6.
However, I get a column vector of 6; 44; 55
Walter Roberson
Walter Roberson 2011 年 9 月 23 日
hint: ismember
Kyle
Kyle 2011 年 9 月 23 日
Sorry, Im confused about the hint.
Walter Roberson
Walter Roberson 2011 年 9 月 23 日
You have determined the n highest values. Now, how are you going to test each value in x to determine whether it is one of those high values?
Kyle
Kyle 2011 年 9 月 23 日
Im sorry but I really don't know. I'm new to MatLab and am really confused.
Walter Roberson
Walter Roberson 2011 年 9 月 23 日
So... read the documentation on the function named "ismember"
Kyle
Kyle 2011 年 9 月 23 日
So would it be something like select = ismember(select,y_largest_x)?
When I do that i get and = 0 0 0 0 0 0
Walter Roberson
Walter Roberson 2011 年 9 月 23 日
Consider:
if ismember(SOMETHING(5),y_largest_x)
select(5) = x(5);
end
Now figure out what SOMETHING should be.
Kyle
Kyle 2011 年 9 月 23 日
I don't know, xsorted?
Walter Roberson
Walter Roberson 2011 年 9 月 23 日
No.
It is difficult to give any more hints without giving the key answer away, which would ruin the purpose of the assignment.
The entire assignment can be completed with two statements plus the function header. Ah yes... I just remembered the hack that would allow it to be written as a single statement plus the function header.
Daniel Shub
Daniel Shub 2011 年 9 月 25 日
This sounds like another challenge to see how few characters are needed ...

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

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

質問済み:

2011 年 9 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by