i am trying to write a function to find the second max number

can you edit this code so it can find the second max number
function [SeMax] = SecondMax(v)
n = numel(v);
res = sort(v);
for k = 1 : 1: n
res = v(1,end-1);
end
end

댓글 수: 5

That sounds like homework.
Why are you bothering to sort v and assign the result to res if you are going to overwrite all of res each time through the loop after that?
Your function is defined as returning the value of SeMax but you never assign a value to that variable.
Suppose that the vector contains two copies of the same maximum number. For example [5 -1 5 3], which would sort to [-1 3 5 5] . Then if you remove the maximum number at the end, you would get [-1 3 5] . Would it be okay that the 5 left at the end is considered the second maximum number, or does the second maximum number have to be a number that is distinct from the maximum number?
What should your code do if all of the entries in the vector are the same?
do you know how to do it ???!
Yes, I do know how to do any of those possibilities, but I do not know yet what the requirements are for your assignment.
Let us start with something simple: if the input is the single number 7, then what does the output have to be? Next, if the input is [7 7], then what does the output have to be? Next, if the input is [7 7 9], then what does the output have to be?
Jan
Jan 2018년 6월 12일
편집: Jan 2018년 6월 12일
And what is wanted for [7 9 9]?
Maybe the unique command helps.

댓글을 달려면 로그인하십시오.

답변 (1개)

Paridhi Yadav
Paridhi Yadav 2018년 6월 12일
In your function you can write
res = sort(v)
SeMax = res(end-1)
It will give you the last second value after sorting, which is second largest if last and second last values are not same.

댓글 수: 1

It is useful not to post solutions of homework questions. But you are suggesting only code, which was posted by the OP already. That's okay. +1

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Functions에 대해 자세히 알아보기

질문:

2018년 6월 12일

댓글:

Jan
2018년 6월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by