問題は、次の場合です。
Vector(i) = []
配列のサイズを変更すると、最初に探していない結果が生成され、次にコード内の if 条件がスクリプトの範囲外への移動を妨げません。これを解決する 1 つの方法は、補助ベクトルを使用することです。
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
常に最後の要素を保持したいと思っていることに注意してください。
for ループを回避したい場合は、次のこともできます。
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)