How to delete elements in array efficiently
17 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Azzi Abdelmalek
2013-8-25
Vector=[1 2 4 5 66 88 100 101]
id=find([0 diff(Vector)]==1)-1
Vector(id)=[]
0 个评论
更多回答(2 个)
Azzi Abdelmalek
2013-8-25
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!