Inputs a Vector and Returns the Second Smallest Element

조회 수: 3 (최근 30일)
Sophie Culhane
Sophie Culhane 2020년 9월 17일
답변: James Tursa 2020년 9월 17일
I am writing a script that takes as input a nonempty vector v and returns the second smallest element. I have a block of code written that runs, however it does not compute the correct answer. I am not sure why the program does not run correctly.
Here is what I have:
function SecondSmallest = ex1(v)
%
%
vLength = length(v);
Smallest = v(1);
CurrentPosition = 2;
while CurrentPosition <= vLength
if v(CurrentPosition) <= Smallest
Smallest = v(CurrentPosition);
SecondSmallest = v(1);
else
Smallest = v(1);
SecondSmallest = v(CurrentPosition);
end
CurrentPosition = CurrentPosition + 1;
end

답변 (1개)

James Tursa
James Tursa 2020년 9월 17일
Your algorithm always replaces Smallest and SecondSmallest at each iteration. Does that make sense? E.g., if the current Smallest = 5 and SecondSmallest = 7, and v(CurrentPosition) = 10, should your algorithm be replacing either of them? No, it shouldn't. But your algorithm does. You need to step through this one line at a time with a small example vector to see what is going wrong and change your logic. In some iterations your algorithm should not be replacing either of Smallest or SecondSmallest. So the if-test inside your loop should have logic for doing nothing. E.g.,
if( v(CurrentPosition) < Smallest )
% do something
elseif( v(CurrentPosition) < SecondSmallest )
% do something
end
With the above logic, if neither of the tests is satisfied, then nothing is done to Smallest or SecondSmallest.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by