Clear Filters
Clear Filters

Hi I need help with this problem in MATLAB CODE!

2 views (last 30 days)
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 Comments
Hildo
Hildo on 28 Nov 2016
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 on 28 Nov 2016
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.

Sign in to comment.

Accepted Answer

bio lim
bio lim on 28 Nov 2016
Edited: bio lim on 28 Nov 2016
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.

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!