MATLAB Answers

0

Getting rid of a for loop

Asked by jacob Mitch on 19 Oct 2019 at 21:56
Latest activity Commented on by jacob Mitch on 20 Oct 2019 at 17:10
If I have my code as
function [value1, value2] = scope(input)
c=1;
x=length(input);
for z=2:x
if z==x
break
elseif input(z-1)>input(z) && input(z)<input(z+1)
value1(c,1)=z;
value2(c,1)=input(z);
c=c+1;
end
end
Is it possible to get rid of the for look so the function runs without loops. Thank you.

  0 Comments

Sign in to comment.

3 Answers

Answer by Walter Roberson
on 19 Oct 2019 at 23:37
 Accepted Answer

value1 = find(input(1:end-2) > input(2:end-1) & input(2:end-1) < input(3:end)) + 1;
value2 = input(value1);

  1 Comment

jacob Mitch on 20 Oct 2019 at 17:10
Perfect Walter, Thank you

Sign in to comment.


Answer by Turlough Hughes on 19 Oct 2019 at 23:38
Edited by Turlough Hughes on 19 Oct 2019 at 23:43

The following should do the job.
ind=input(1:end-2)>input(2:end-1) & input(2:end-1)<input(3:end);
ind=[false; ind; false]; % If input is a row vector just remove to semi-colons here.
value1=find(ind);
value2=input(ind);

  0 Comments

Sign in to comment.


Steven Lord
Answer by Steven Lord
on 20 Oct 2019 at 0:01

You're looking for a local minimum in your vector input? [I would choose a different name, BTW, since input already has a meaning.] If so and you're using release R2017b or later use islocalmin.

  0 Comments

Sign in to comment.