2011-12-06 42 views
0

我有一個矩陣A:Matlab的切邊在界

楠楠楠楠楠楠的NaN 10 1 8 7 2 5 6 2 3 49楠楠楠楠楠楠

我想知道是否有一種方法來檢測NaN首先轉向數字並將第一個2點轉換爲NaN,例如NaN。

然後找到什麼時候數字轉到NaNs並將最後兩個數字點,3和49轉換爲NaN。

本來我想用下面的,但我想知道如果這是最好的辦法:

i= 2; 
while i < 1440 
    if isnan(A(i)) < isnan(A(i-1))  //Transitioning from NaN to numbers 
     A(i:i+2) = NaN; 
     i = i+ 4; 
    elseif isnan(A(i)) > isnan(A(i-1)) //Transitioning from numbers to NaNs 
     A(i-2:i) = NaN; 
     i = i + 1; 
    else 
     i = i + 1; 
    end 
end 

,但不知道是否有我可以優化它的任何其他方式?

回答

3

首先,我認爲你的載體A與NaN的在開始和結束,一個連續集,中間數字組成組織,如

A = [NaN ... NaN, contiguous numeric data, NaN ... NaN] 

首先,我建議定位的數字數據,並從工作還有,如,

flagNumeric = ~isnan(A); 

現在flagNumeric將是一個真正的是數字條目和NaN's

因此,第一個數字將在

firstIndex = find(flagNumeric,1,'first'); 

最後數字以

lastIndex = find(flagNumeric,1,'last'); 

然後可以使用firstIndexlastIndex的改變第一和最後一個數字數據NaN's

A(firstIndex:firstIndex+1) = NaN; 
A(lastIndex-1:lastIndex) = NaN; 
1
% Set the first two non-NaN numbers to NaN 
first = find(isfinite(A), 1, 'first'); 
A(first:first+1) = NaN; 

% Set the last two non-NaN numbers to NaN 
last = find(isfinite(A), 1, 'last'); 
A(last-1:last) = NaN; 

當然,上述代碼會在特殊情況下中斷(例如,當last == 1),但這些應該是直截了當的過濾掉。

1

下面是基於相同的假設阿齊姆的回答稍微簡單的版本:

nums = find(~isnan(A)); 
A(nums([1 2 end-1 end])) = NaN;