Getting rid of a for loop

3 ビュー (過去 30 日間)
jacob Mitch
jacob Mitch 2019 年 10 月 19 日
コメント済み: jacob Mitch 2019 年 10 月 20 日
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.

採用された回答

Walter Roberson
Walter Roberson 2019 年 10 月 19 日
value1 = find(input(1:end-2) > input(2:end-1) & input(2:end-1) < input(3:end)) + 1;
value2 = input(value1);
  1 件のコメント
jacob Mitch
jacob Mitch 2019 年 10 月 20 日
Perfect Walter, Thank you

サインインしてコメントする。

その他の回答 (2 件)

Turlough Hughes
Turlough Hughes 2019 年 10 月 19 日
編集済み: Turlough Hughes 2019 年 10 月 19 日
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);

Steven Lord
Steven Lord 2019 年 10 月 20 日
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.

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by