Increment loop index based on a condition

조회 수: 6 (최근 30일)
A VP
A VP 2017년 12월 26일
편집: A VP 2018년 1월 2일
I have an array that has 100000+ values. every 3000th sample to a new array based on a condition.
1. I should compare every 3000th value and see if it differs from the previous 3000th sample by greater than 10. If so, I should add the sample, sample+100th element, sample+200th element to my new array.
2. If not, I should only add the 3000th sample element to my new array and then move to the next 3000th sample.
I have implemented this as an if-else loop inside a for loop. My problem is I am unable to increment the loop index if I first enter the if-loop and then go to the else loop next. I have tried using a while loop instead;however, the while loop executes forever and I don't get any output.
Any help is appreciated.
Thanks.

채택된 답변

Walter Roberson
Walter Roberson 2017년 12월 26일
output = [];
for K = 6000 : 3000 : length(YourVector)
if abs(YourVector(K) - YourVector(K-3000)) > 10
output = [output, YourVector(K+[0 100 200])];
else
output = [output, YourVector(K)];
end
end
  댓글 수: 1
A VP
A VP 2017년 12월 27일
Thank you. This helped me solve the problem!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

A VP
A VP 2018년 1월 2일
편집: A VP 2018년 1월 2일
Now I have an added condition to this problem : 1. I should compare every 3000th value and see if it differs from the previous 3000th sample by greater than 10. If so, I should add the sample, sample+100th element, sample+200th element, sample+300th element, sample+400th element, sample+500th element to my new array.
If one of the (sample+100th element, sample+200th element, sample+300th element, sample+400th element, sample+500th element) in the same order are different from any of the previous samples by 10, then I have to add the next 5 samples to the array. For eg : if (sample+300)-(sample+100)>10, then the new array becomes [output, sample+100, sample+200, sample+300,sample+400,sample+500,sample+600,sample+700,sample+800];
eg2 : if ((sample+500)-(sample+200)>10), then the new array becomes [output, sample+100, sample+200, sample+300, sample+400,sample+500,sample+600,sample+700,sample+800,sample+900,sample+1000];
This should continue inside a loop.
What I have now is this :
for i = 6000 : 3000 : length(YourVector)
if abs(YourVector(i) - YourVector(i-3000)) > 10
output = [output, YourVector(i+[0 100 200 300 400 500])];
if abs(YourVector(i+100) - YourVector(i+500)) > 10
output = [output, YourVector(i+[0 600 700 800 900 1000])];
end
else
output = [output, YourVector(i)];
end
I am only able to compare the extreme elements for this, not any of the intermediate elements. Any help is appreciated.
Thank you.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by