Return true if the elements of the input vector increase monotonically (i.e. each element is larger than the previous). Return false otherwise.
6 views (last 30 days)
Show older comments
Return true if the elements of the input vector increase monotonically (i.e. each element is larger than the previous). Return false otherwise. this is my code
function tf = mono_increase(x)
% we need to check every number
L=length(x);
% we nust use for loop
% then we must use if statement
if L==1
tf=true; % adding a condition for single element
return %we must close the case for faster operation
end
for ii = 1:(L-1)
if x(ii+1) > x(ii) % we have problems in the -ve numbers
tf= true ;
else
tf=false ;
end
end
it doesn't work for negative numbers like : input x= [ -3 -4 1 2 4] the output must be false but I get true I think the wrong is in the indexing
0 Comments
Accepted Answer
Jeffrey Eymer
on 28 Jun 2018
for ii = 1:(L-1)
if x(ii+1) > x(ii) % we have problems in the -ve numbers
tf= true ;
else
tf=false ;
end
end
Look at this portion of the code. For each ii in 1:(L-1), this portion of code gets called. This means that the value of tf is being updated 'L' number of times (i.e., when checking every pair of elements).
For example, the last two elements in [ -3 -4 1 2 4] are 2 and 4, which are monotonically increasing. Therefore, on the last iteration the value of tf is set to true and is not affected by the rest of the input.
You should try rewriting your code in a way where the value of tf is only updated to false when an issue is found.
2 Comments
D. Plotnick
on 28 Jun 2018
Edited: D. Plotnick
on 28 Jun 2018
You really want to try to avoid loops, especially for relatively simple operations like this. In this case, you can use a break to stop at the first non-monotonic jump, but the code is way clunkier and a bit slower.
% Set up spaces
x1 = linspace(0,1,1000001).'; % Column it
x2 = rand(1000001,1);
% Using any
tic;
dx1 = diff(x1);
tf1 = ~any(dx1<=0)
dx2 = diff(x2);
tf2 = ~any(dx2<=0)
toc
% Versus loops:
tic
tf1 = true;
tf2 = true;
for ii = 1:length(x1)-1
if x1(ii) >= x1(ii+1)
tf1 = false;
break
end
end
tf1
for ii = 1:length(x2)-1
if x2(ii) >= x2(ii+1)
tf2 = false;
break
end
end
tf2
toc
The any method requires just 2 lines to execute.
Note too that using any you can also return the indices of the bad numbers
function [tf,inds] = ismonotonic(x)
dx = diff(x);
inds = dx<=0;
tf = ~any(inds);
end
More Answers (1)
D. Plotnick
on 28 Jun 2018
Edited: D. Plotnick
on 28 Jun 2018
One idea: dx = diff(x); tf = ~any(dx<=0);
Note this will also work on matrices, if you want. E.g. to look at each row
x = {some numbers}; dx = diff(x,2); tf = ~any(dx<=0,2);
Here, tf will return a column of logicals.
0 Comments
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!