2013-08-25 100 views
0

我正在寫在Matlab一個簡單的腳本,其中我比較相鄰元件和刪除其中之一是否有它們之間的差別是一個。在陣列中刪除元素,索引超出範圍(Matlab的)

for i=1:length(Vector) - 1 
if Vector(i+1) - Vector(i) == 1 
    Vector(i) = []; 
end 
if i == length(Vector) 
    break 
end 

不過,我發現了一個錯誤,我的指標是出界。我不知道爲什麼,我的算法似乎應該工作。有沒有更簡單的方法來使用內部函數來做到這一點?

回答

3

的問題是,當你這樣做:

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) 
0

我覺得這

如果矢量(i + 1) - 矢量(i)== 1

,當你有大小1索引i的載體可能是問題+ 1不存在

+0

,我認爲你是對的。也許有是不是以這種方式 – l3win

2

pabaldenedo是正確的,問題是消除在迭代的中間分子。

更好的解決方案是簡單地矢量化搜索和清除:

mask = [diff(Vector) == 1, 0]; % find elements where the step is 1 
Vector = Vector(~mask);  % exclude them 

這也應該是快了很多。

如果當他們是比現有元素的一個更大的重複的元素應該被刪除,你可以重複。不幸的是,MATLAB沒有do-while循環。

mask = [diff(Vector) == 1, 0]; % find elements where the step is 1 
while any(mask)    % if we found elements to exclude 
    Vector = Vector(~mask);  % exclude them 
    mask = [diff(Vector) == 1, 0]; % search again 
end 
+0

爲什麼你必須包括在第一線的矢量零比較元素這樣做的更好的辦法?掩模= [DIFF(向量)== 1,0] – l3win

+0

沒關係,得到它,THX – l3win