I need to create a sort function without using inbuilt functions like sort min or max, to sort a 3 element vector?

This is what I have come up with
function [x, y, z] = sortstuff(t)
if t(1,1)<=t(1,2) && t(1,2)<=t(1,3);
x = t(1,1);
y = t(1,2);
z = t(1,3);
elseif t(1,1)<=t(1,2)&& t(1,2)>=t(1,3) && t(1,1)<=t(1,3);
x = t(1,1);
y = t(1,3);
z = t(1,2);
elseif t(1,1)>=t(1,2) && t(1,2)<=t(1,3) && t(1,1)<=t(1,3);
x = t(1,2);
y = t(1,1);
z = t(1,3);
elseif t(1,1)<=t(1,2) && t(1,2)>=t(1,3) && t(1,1)>=t(1,3);
x = t(1,3);
y = t(1,1);
z = t(1,2);
elseif t(1,1)>=t(1,2) && t(1,2)<=t(1,3) && t(1,1)>=t(1,3);
x = t(1,2);
y = t(1,3);
z = t(1,1);
elseif t(1,1)>=t(1,2) && t(1,2)>=t(1,3);
x = t(1,3);
y = t(1,2);
z = t(1,1);
end
This works well for horizontal vector but not for vertical vector. Please advise.

回答(1 个)

Of course, it does not work for column vectors. It also does not work for vectors along the 3rd, 4th, etc. dimension. You used subscript indexing (2D) and specifically told matlab to look for values in the first row only. Unless the vector is a row vector, there's only one value in that first row.
The solution is simple, use linear indexing, which you always should use with vectors unless you have a particular reason for your code to only work with vectors along a particular dimension. With linear indexing it does not matter if the vector is a column, row, or along any other dimension.
So:
if t(1) <= t(2) && t(2) <= t(3)
%and so on...
It makes the code a lot more readable as well.
edit: Also note that when you have a series of if ... elseif ... elseif ..., the last one should be an else, not an elseif. In your case, the last elseif is guaranteed to be true if all the other elseif weren't (Unless one of the number is NaN, then you're in trouble since your code will not assign anything to the outputs).

类别

在 帮助中心 和 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