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!!
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!