Hi I need help with this problem in MATLAB CODE!

2 次查看(过去 30 天)
Hi! I have a problem! I don't know how to do this in MATLAB CODE: Write a function in Matlab that receives a vector and determine if the numbers within the vector are ordered from least to greatest. The output must be a single variable that takes a value of 1 when the numbers are ordered or 0 (zero) otherwise.Write 2 versions of the function. One using "loops" and the other using vector operations (not "loops").Thanks a lot!
  2 个评论
Hildo
Hildo 2016-11-28
This appear to be a simple already solved problem. If I understand right you just have to use the function
issorted(X)
If you need to test the opposite order use
issorted(X(end:-1:1))
Steven Lord
Steven Lord 2016-11-28
If as I suspect this is homework and you are not allowed to use the issorted or sort functions, show what you've done to try to solve the problem and describe where you're having difficulty and we may be able to offer some guidance.

请先登录,再进行评论。

采纳的回答

bio lim
bio lim 2016-11-28
编辑:bio lim 2016-11-28
Loop version:
function Y = coffee(X)
Y = zeros(length(X)-1,1);
for i=1:(length(X)-1)
if X(i+1) >= X(i)
Y(i) = 1;
else Y(i) = 0;
end
end
if Y == 1
Y = 1;
else Y = 0;
end
end
Test:
vec = [1 7 6 2 8 9 10];
vec2 = [1 2 3 4 5];
vec = coffee(vec);
vec2 = coffee(vec2);
The output is:
vec =
0
vec2 =
1
Non-loop version: (As Hildo suggested)
function Y = coffee(X)
if issorted(X)
Y = 1;
else Y = 0;
end
And the output is the same. Moreover, as Steven Lord suggested, I doubt you are allowed to use issorted or sort function if this is a homework. I leave that part up to you since you have the basic idea now.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by