的問題是,當你這樣做:
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