How to have an arbitrary vector as your input for your function?

10 次查看(过去 30 天)
Currently have the following snippet of my code:
function output =sort3(A)
A= [a b c]
if (a<=b)&& (b<=c)
if a<b && b<c
output= [a b c]
What I'm trying to do here is be able to input any arbitrary vector (e.g. [1 2 3]) and have the output follow the parameters that are listed within my code. I keep getting the error: undefined function or variable 'a'... I'm super new to Matlab, so how could I fix my code to have it be able to input any arbitrary vector?
Thanks!!

采纳的回答

Geoff Hayes
Geoff Hayes 2017-8-20
Hye - if A is a vector of (say) three elements, then to access the first element you would do A(1), the second element A(2), and the third as A(3). With your code, you seem to be trying to assign the elements of A to variables
A = [a b c]
and MATLAB is (rightly) throwing the error that a is undefined. See Array Indexing for more details on how to access the elements of your (arbitrary) input array.
If you are trying to design a sorting algorithm, then you may want to consider iterating over each element in your array (this may require two loops) comparing the kth element to the (k-1)th. See for loop for more information. For example,
for u=1:length(A)
for v=2:length(A)
if A(v) < A(u)
% do something
end
end
end
  2 个评论
Hye Sun Choi
Hye Sun Choi 2017-8-20
Hey! Thanks for your response. So what I'm trying to do is write a function that takes a 3-element vector as its sole arguments, and I want the 3 elements of the vector to return 3 scalar output arguments in a non-decreasing way...
So this is why I did the following:
function output =sort3(A)
A= [a b c]
if (a<=b)&& (b<=c)
if a<b && b<c
output= [a b c]
And the code goes on. But with your response, which I might be interpreting it incorrectly, we would have to know which vectors we're inputting beforehand if we wanted to put the element as A(1) i.e. we would have to know that the first element is one?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by