Not displaying a 3 element vector as a result of my function? Any advice?

2 views (last 30 days)
Hi! I am supposed to write a function that takes a 3-element vector as its sole arguments. It uses if- statements, possibly nested, to return a 3-element vector with its elements in non-decreasing order,and doesn't use any predefined functions. This is the code I have so far. It will display the lowest element, but not the other two. For example, if I make my V=[2 1 3], it will give ans=1. How do I make it display 1 2 3 in the correct order? Here's my code:
function [x, y, z]= mysort(V)
a=V(1);
b=V(2);
c=V(3);
if (a<=b && a<=c)
x=a;
if (b<=c)
y=b;
z=c;
else
y=c;
z=b;
end
end
if (b<=a && b<=c)
x=b;
if (a<=c)
y=a;
z=c;
else
y=c;
z=a;
end
end
if (c<=b && c<=a)
x=c;
if (b<=a)
y=b;
z=a;
else
y=a;
z=b;
end
end
end

Accepted Answer

Star Strider
Star Strider on 9 Mar 2018
If you only ask for one output of a function that has more than one output, MATLAB will only return the first output. You have to ask for all of them in order to return all of them.
Your function works correctly. Try this:
V=[2 1 3];
[X,Y,Z] = mysort(V)

More Answers (1)

Community Treasure Hunt

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

Start Hunting!