Help debugging a code? Says function makes an error but when I run it, it returns the correct output...

I'm having trouble with the following assignment:
Write a function called sort3 that takes a 3-element vector as its sole arguments. It uses if-statements, possibly nested, to return the three elements of the vector as three scalar output arguments in non- decreasing order, i.e., the first output argument equals the smallest element of the input vector and the last output argument equals the largest element. NOTE: Your function may not use any built-in functions, e.g., sort, min, max, median, etc.
Here is what I've done so far:
function [a,b,c]=sort3(A)
a= A(1); b=A(2); c=A(3);
if (a<=b)&& (b<=c)
if a<b && b<c
output= [a b c]
elseif(a==b)&& b<c
output= [a b c]
elseif a<b && (b==c)
output= [a b c]
else a==b==c
output= [a b c]
end
elseif (a<= c)&& (c<=b)
if (a<c)&& (c<b)
output= [a c b]
elseif (a==c)&& a<b
output= [a c b]
elseif a<c && (c==b)
output= [a c b]
else a==c==b
output= [a c b]
output = [a c b]
end
elseif (b<=c) && (c<=a)
if b<c && c<a
output= [b c a]
elseif (b==c)&& c<a
output= [b c a]
elseif b<c &&(c==a)
output= [b c a]
else b==c==a
output= [b c a]
end
elseif (b<=a) && (a<=c)
if b<a && a<c
output= [b a c]
elseif (b==a)&& b<c
output= [b a c]
elseif b<c &&(c==a)
output= [b a c]
else b==c==a
output= [b a c]
end
elseif (c<=a) && (a<=b)
if c<a && a<b
output= [c a b]
elseif (c==a)&& a<b
output= [c a b]
elseif c<a && (a==b)
output= [c a b]
else c==a==b
output= [b c a]
end
else (c<=b) && (b<=a)
if c<b && b<a
output= [c b a]
elseif (c==b)&& b<a
output= [c b a]
elseif c<b && (b==a)
output= [c b a]
else b==c==a
output= [b c a]
end
end
I ran it through an autograder and it said:
Feedback: Your function performed correctly for argument(s) [1 2 3]
Feedback: Your function made an error for argument(s) [1 3 2]
But when I set A= [1 3 2], it seems to return the output [1 2 3].
Also -- I totally realize that my code is very inefficient. What are some ways I could make my code more efficient?
Thank you!

回答(1 个)

IMO: Your code is a nightmare to debug and I will not try.
There is a problem with output. It's not used as output.
function [a,b,c]=sort3(A)
by
function varargout = sort3(A)
and all the
output = [ ...]
by
varargout = { ... }; % e.g.
varargout = { b, c, a };
If that doesn't help see Bubble sort
In response to comment:
Add this line at the end of your code
a = out(1); b = out(2); c = out(3);
Replace
else b==c==a
by
elseif b==c && c==a
or whatever it's intended to be

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by