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 Comments

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.

Sign in to comment.

 Accepted Answer

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 Comments

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!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 22 Nov 2016

Commented:

on 22 Nov 2016

Community Treasure Hunt

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

Start Hunting!