2016-06-12 129 views
0

我有一個數列爲1至8的列向量。在正常情況下,每個數字有4個連續值,從1移至8,即: Perfect_sample = [1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8]';識別並標記連續重複的數據MATLAB

圖案再次從一個所述8.

但是之後開始,有時也有缺失值和矢量看起來不象上面的一個,但,例如,像這樣:

Imperefect_sample=[1 1 2 2 2 3 3 3 3 4 5 5 5 5 6 7 7 7 7 8 8]'; 

我的目標是與NaN的替換每個連續組相同的號碼的前兩個值:

Perfect_sample_result=[NaN NaN 1 1 NaN NaN 2 2 NaN NaN 3 3 NaN NaN 4 4 NaN NaN 5 5 NaN NaN 6 6 NaN NaN 7 7 NaN NaN 8 8]' 

如果只有兩個或更少的連續的相同的數字,那麼這些數字應該用NaN代替。

Imperfect_sample_result=[NaN NaN NaN NaN NaN NaN 2 2 NaN NaN 3 3 NaN NaN NaN NaN NaN NaN 5 5 NaN NaN NaN NaN NaN NaN 7 7 NaN NaN NaN NaN]' 

我該如何做到這一點?

+3

您能否提供一個具有「兩個或更少」連續數字的示例,因爲您發佈爲「Imperefect_sample」的數據與結果完全不符。除非它......?目前還不清楚。 – Suever

+0

@Suever不完美的樣本具有兩個或更少的連續相同的數字,從1,46和8開始。我添加了Imperfect_sample_result。 – Buzz

+0

@Buzz爲什麼你在2之前有5個nans? – drorco

回答

1

根據我的理解,這將工作。請記住,它沒有考慮任何大於4的事件,因爲你沒有提到這是可能的。這是基於我從您的原始帖子中瞭解的內容。

clc 
clear 
Imp=[1 1 2 2 2 3 3 3 3 4 5 5 5 5 6 7 7 7 7 8 8]; 
perf = Imp; 
pos = 1; % position of your cursor 
while(pos<max(size(perf))-2) % -2 to avoid going out of range 
next = true; %check if it should go further 
count = 0; % will store number of consecutive times the iith number appears 

    while(next == true) %checks if the next digit in the sequence is the same 
     if(perf(pos) == perf(pos+count)) 
      count = count+1; 
     else 
      next = false; 
     end 

    end 


if (count == 1) 
    perf(pos) = NaN; 
elseif(count == 2) 
    perf(pos:pos+1) = NaN; 
elseif(count == 3) 
     perf(pos:pos+2)= NaN; 
elseif(count == 4) 
     perf(pos:pos+1)= NaN; 
    end 

pos = min(pos+ count,max(size(perf))); % passes the counter to the next value 
end 
+0

非常感謝。你的解決方案完美運作 – Buzz