필터 지우기
필터 지우기

Truncation of a vactor

조회 수: 2 (최근 30일)
Mohammad Sayeed
Mohammad Sayeed 2014년 4월 8일
댓글: Mohammad Sayeed 2014년 4월 8일
Hello
I have a vector like this x=[4 7 17 4 6 9 12]
I need to get rid of any values which are higher than 10. I tried this:
for i=1:length(x);
if x(i)>10 x(i)=[];
end
end
This works but with this error message:
'Attempted to access x(7); index out of bounds because numel(x)=5.'
How can I do it without any error message because I need to compute further with x.
Can anyone help?
Kind regards
Sayeed

채택된 답변

Walter Roberson
Walter Roberson 2014년 4월 8일
After you delete x(3) then what was at x(4) "falls down" to occupy x(3), what was at x(5) "falls down" to x(4), and so on, leaving x one element shorter. You then go to the next "i" element, 4, examining what is now in x(4) which was in x(5)... and you have skipped examining what was in x(4) and is now in x(3).
Eventually you get to the point where you have deleted the last entry in x, making x two elements shorter, but your "for" loop over length(x) is going to be based on the original length of x, so you are going to end up attempting to access after the last element of what x has become.
Lesson: if you delete elements of a vector using a forward-going loop, you need to take into account that the remainder of the vector moves down to fill up the hole. You can code that in, or you can recode to avoid using a loop to delete elements, or you can try your hand at using a loop that does not go forward.
  댓글 수: 1
Mohammad Sayeed
Mohammad Sayeed 2014년 4월 8일
Thanks for your valuable insights. That helps.

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

추가 답변 (1개)

ES
ES 2014년 4월 8일
Or in other words, you might do
x(x>10)
  댓글 수: 1
Mohammad Sayeed
Mohammad Sayeed 2014년 4월 8일
Yes that works, x(x>10)=[]; No need to make any loop
Thank you very much.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by