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에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

질문:

2016년 11월 22일

댓글:

2016년 11월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by