How to delete elements in array efficiently

Hi all,
I'm writing a simple script in Matlab where I compare adjacent element and delete one of them if there difference between them is one.
for i=1:length(Vector) - 1
if Vector(i+1) - Vector(i) == 1
Vector(i) = [];
end
if i == length(Vector)
break
end
However, I'm getting an error that my indices are out of bound. Is there a simpler way of doing this by utilizing internal functions. I think my problem is that my array is constantly decreasing and the Vector(i+1) - Vector(i) are out of bounds.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 25일

2 개 추천

Vector=[1 2 4 5 66 88 100 101]
id=find([0 diff(Vector)]==1)-1
Vector(id)=[]

추가 답변 (2개)

dpb
dpb 2013년 8월 25일
편집: dpb 2013년 8월 25일

2 개 추천

When doing such in loops, start at end and work to beginning -- then the indices of those removed are above where you're headed next.
But, in Matlab use vector operations and supplied functions to do such things...
v([false diff(v)==1])=[];
Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 25일

0 개 추천

You can also do it with while loop
Vector=[1 2 3 4 5 66 88 100 101 14]
i=1;
while i<numel(Vector)
if Vector(i+1) - Vector(i) == 1
Vector(i) = [];
i=i-1;
end
i=i+1
end
Vector

댓글 수: 4

Or, variations on a theme, the looping solution...
for i=length(v):-1:2
if v(i)-v(i-1)==1;
v(i)=[];
end
end
The result is not the same, because this will keep the first number of the consecutive numbers
Jan
Jan 2013년 8월 25일
Repeated shrinking of an array suffers from the same inefficiency as iterative growing.
dpb
dpb 2013년 8월 26일
Posted simply as pedagogical example for OP, not as recommended solution--see earlier posting.

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

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

질문:

ste
2013년 8월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by