How do I create a function that accepts a 3 element vector as input, but returns scalar values?

I need to create a function that sorts the order of a vector elements and returns it as scalar values.

3 个评论

Please give an example of an input vector and desired output.
[1 2 3] as input (how do you command this input?) and scalar values 1 2 3 as output (how do you distinguish that from the original vector?)
I feel like I need to be using nargin or varargin but am unsure how to implement them, and the ways I've tried haven't worked.

请先登录,再进行评论。

 采纳的回答

If I understand you correctly, here is an outline of such a function (in a file called sort3.m):
% Filename sort3.m
function [a,b,c] = sort3(x)
% your code for sorting goes here
a = whatever
b = whatever
c = whatever
end
You need to fill in the actual sorting code.

3 个评论

Thank-you. I edited my code to the following but it's still not working:
function [x,y,z] = sort3(t)
if x<=y && y<=z
t = [x y z];
elseif x>=y && y>=z
t = [z y x];
elseif x<=y && y>=z && x<=z
t = [x z y];
elseif y>=z && x<=y
t = [z x y];
elseif y<=x && x<=z
t= [y x z];
elseif y<=x && z<=x
t = [y z x];
end
end
Your code is written backwards. The variable t is the input, so you need to work with t(1), t(2), and t(3). Your code should be comparing these values and then assigning the output to x, y, and z, not the other way around. E.g.,
if t(1) <= t(2) && t(2) <= t(3)
x = t(1);
y = t(2);
z = t(3);
etc.
I had a feeling I was making a silly mistake...it worked, thank-you!

请先登录,再进行评论。

更多回答(0 个)

类别

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