- You need to return true/false - not as string
- You compare values to be bigger or equal -> [1 1 1] is not increasing, but your solution return true
- Your solution wont work with single values, because x(i+1) does not exist

9 views (last 30 days)

Show older comments

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?

Dennis
on 30 Jul 2018

There are a few problems with your solution:

- You need to return true/false - not as string
- You compare values to be bigger or equal -> [1 1 1] is not increasing, but your solution return true
- 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

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

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

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

Start Hunting!