的问题是,当你这样做:
Vector(i) = []
你改变哟大小UR阵列,并且将首先产生一个结果,你是不是在找和第二代码后面的,如果条件不阻止脚本去出界。解决这个问题的一种方法是使用辅助矢量。
Vector = [1,5,6,3,5,7,8,9];
tmp = [];
j = 1;
for i=1:length(Vector)-1
if Vector(i+1) - Vector(i) == 1
continue
end
tmp(j) = Vector(i);
j = j + 1;
end
tmp(end+1) = Vector(end);
Vector = tmp
请注意,我假设你总是想保留最后一个元素。
如果你想避免循环,你也可以这样做:
Vector = [1,5,6,3,5,7,8,9];
tmp = circshift(Vector, [0,-1]); %shifted version of Vector
tmp(end) = Vector(end)+2; %To ensure that the last element will be included
index = tmp-Vector ~= 1; %indices that satisfy the condition
Vector = Vector(index)
,我认为你是对的。也许有是不是以这种方式 – l3win