How to find the index of the variable in my For Loop when a condition is met
조회 수: 8 (최근 30일)
이전 댓글 표시
Serena Simpson
2020년 10월 2일
편집: Asad (Mehrzad) Khoddam
2020년 10월 2일
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
댓글 수: 0
채택된 답변
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
댓글 수: 0
추가 답변 (1개)
Asad (Mehrzad) Khoddam
2020년 10월 2일
Use
[nf, ind] = find(nr == i);
ind contains the index with the given condition
댓글 수: 2
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 Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!