MATLAB Answers

Problem 10 of MATLAB cody challenge

9 views (last 30 days)
NAVNEET NAYAN
NAVNEET NAYAN on 28 Jul 2018
Edited: Guillaume on 2 Feb 2020
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?

Accepted Answer

Dennis
Dennis on 30 Jul 2018
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
  3 Comments
NAVNEET NAYAN
NAVNEET NAYAN on 31 Jul 2018
thanks Guillaume for the worthy suggestions.

Sign in to comment.

More Answers (2)

Paolo
Paolo on 28 Jul 2018
You can use:
all(diff(x)>0)
  4 Comments
Paolo
Paolo on 1 Aug 2018
Thanks for the detailed answer Guillaume.
Very interesting indeed, those are some cool tricks. Wouldn't have thought people had put all this effort into hacking cody!

Sign in to comment.


Sriram Nayak
Sriram Nayak on 2 Feb 2020
i=1;
while i<length(x)
if x(i)<=x(i+1)
tf='true';
else
tf='false';
break;
end
%
i=i+1;
end
  1 Comment
Guillaume
Guillaume on 2 Feb 2020
I'm afraid this is is not going to work. The char array `true` and the logical value true are not the same at all.
In term of cody score
i = 1;
while i < endbound
%do something
i = i + 1;
end
is going to score you very badly against the equivalent and much simpler for loop:
for i = 1:endbound
%dosomething
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!