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 件のコメント

James Tursa
James Tursa 2016 年 11 月 22 日
Please give an example of an input vector and desired output.
AP720
AP720 2016 年 11 月 22 日
[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?)
AP720
AP720 2016 年 11 月 22 日
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.

サインインしてコメントする。

 採用された回答

James Tursa
James Tursa 2016 年 11 月 22 日
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 件のコメント

AP720
AP720 2016 年 11 月 22 日
編集済み: James Tursa 2016 年 11 月 22 日
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.
AP720
AP720 2016 年 11 月 22 日
I had a feeling I was making a silly mistake...it worked, thank-you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing 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