lab2 ex5
You cannot submit for this problem because the homework's deadline is due.
Ex5. The \(k\)-th largest number (5 marks)
Read a row vector of real numbers and a positive integer \(k\) from user input, and output the \(k\)-th largest number in the vector. The vector is non-empty and \(k\) is guaranteed to be less than or equal to the length of the vector.
There are many ways to implement this. Given below is one possible approach for your reference:
- Get the maximum in the vector along with its index.
- Remove it from the vector.
- Repeat the steps above \(k\) times.
Caveat: MATLAB does provide you with a method to remove elements from vectors. However, due to the way vectors are implemented by computers, this kind of operations are actually not computer-friendly. You will learn more about this in VE280. To make your algorithm more efficient, consider using NaN
. Hint: What does max()
do with NaN
?
Sample Test Cases
Input:
[12 7 45 2 19 37]
1
Output:
45
Input:
[12 7 45 2 19 37]
4
Output:
12
Format
You should submit a compressed file containing a Matlab source file ex5.m