How to find the index of the variable in my For Loop when a condition is met

8 ビュー (過去 30 日間)
I wrote code that itterates element by element of the array 'nr'. Nr has 1000 random numbers. I want to display when two of those random numbers are of the same value, and adjacent. I think that works. I then tried to find the index of the value when it meets the condtion, but it doesnt work. I'm pretty stuck, does anyone have any tips?
for i = 1:length(nr)
if (nr(i)==nr(i+1)) %if a element in the array nr is equal to the
% element above it, then it meets the condition
fprintf("%d is adjacent to a number of equal value", i)
find(nr == i)
end
if i == 1000
break
end
end

採用された回答

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 10 月 2 日
[~,ind] = find(diff(nr)==0)
% print indices
for i = ind
fprintf("%d is adjacent to a number of equal value\n", i)
end

その他の回答 (1 件)

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 10 月 2 日
Use
[nf, ind] = find(nr == i);
ind contains the index with the given condition
  2 件のコメント
Serena Simpson
Serena Simpson 2020 年 10 月 2 日
Thanks! But how can I then output/display what thoes indicies are? I tried disp(nf), but it didnt work.
Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 10 月 2 日
編集済み: Asad (Mehrzad) Khoddam 2020 年 10 月 2 日
inseat of loop use:
[~, ind] = find(diff(nr)== 0);
disp(ind)

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by