Code for Monotonically increasing function

Hi All,
Can anyone check the following code snippet and tell me why it fails for the following test cases?
x = cumsum(rand(1,100));
x= [ -3 -2 -1 0 1 2 3]
function tf = mono_increase(x)
for ii=1:length(x)
for jj=(ii+1):length(x)
if x(ii)<x(jj)
tf = true;
else
tf = false;
end
end
end
end
I'm getting the desired result in my laptop but with the compiler of MATLAB , I'm getting error.
Please someone tell me how to resolve it.

댓글 수: 3

Stephen23
Stephen23 2020년 11월 19일
편집: Stephen23 2020년 11월 19일
"I'm getting the desired result in my laptop ..."
I doubt that.
Your code simply overwrites tf on every loop iteration, which is unlikely to give the required result (if the goal is to test that all values are monotonically increasing). You will need to use some logical operation or indexing or something similar to check that all pairs of values fulfill the required condition/s. Two loops is unlikely to be useful, one is enough.
Or you could just use the simple MATLAB approach using diff and one logical comparison.
Swati Sarangi
Swati Sarangi 2020년 11월 19일
@Stephen
With one loop , will not there be an out-of-bound error?
Stephen23
Stephen23 2020년 11월 19일
"With one loop , will not there be an out-of-bound error?"
Not if the loop iterates the correct number of times (hint: one less than the number of elements).

댓글을 달려면 로그인하십시오.

답변 (1개)

KSSV
KSSV 2020년 11월 19일

0 개 추천

x= [ -3 -2 -1 0 1 2 3] ;
function tf = mono_increase(x)
tf = 1 ;
for i = 1:length(x)-1
if x(i+1) < x(i)
tf = 0 ;
break
end
end
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 11월 19일

댓글:

2020년 11월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by