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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by