MATLAB: Problem 10 of MATLAB cody challenge

ascending order of vectorcody challenge

I was trying to solve this question in cody challenge: Problem 10. Determine whether a vector is monotonically increasing. I tried following code:
i=1;
while i<length(x)
if x(i)<=x(i+1)
tf='true';
else
tf='false';
break;
end
%
i=i+1;
end
When I am running this piece of code on MATLAB editor everything is Ok. But when I am submitting this, incorrect answer results. Format to make a function for this problem is given as:
function tf = mono_increase(x)
tf = false;
end
Can anyone sort it out?

Best Answer

There are a few problems with your solution:
  1. You need to return true/false - not as string
  2. You compare values to be bigger or equal -> [1 1 1] is not increasing, but your solution return true
  3. Your solution wont work with single values, because x(i+1) does not exist
A working solution based on your approach might look like this:
if length(x)==1
tf=true;
else
i=1;
while i<length(x)
if x(i)<x(i+1)
tf=true;
else
tf=false;
break;
end
%
i=i+1;
end
end