假設你的數據在本例中提供的是變量x
,您可以使用isnan
和findstr
像這樣:
x = [NaN, NaN, NaN, -1.5363, NaN -1.7664, -1.7475, 123];
~isnan(x)
ans =
0 0 0 1 0 1 1 1
pos = findstr(~isnan(x), [1 1 1]);
之所以使用findstr
像這是我們想找到序列由isnan
返回的邏輯數組中的[1 1 1]
和findstr
將返回此序列出現的輸入數組中位置的索引。
對於您的示例數據,這將返回[]
,但如果您將其更改爲我給出的示例中的數據,則它將返回6,並且您可以使用x(pos:pos+2)
提取連續區域。如果存在超過3個連續值的情況(如果有4個,它將返回[6 7]
)以及存在多個連續區域的情況,您必須小心一點。如果你不需要對這些情況做任何有意義的事情,那麼就使用pos(1)。
如果你要提取的第一相鄰區域,其長度大於或等於3的全部,你可以這樣做:
x = [NaN, NaN, NaN, -1.5363, NaN -1.7664, -1.7475, 123, 456, 789];
startPos = [];
stopPos = [];
pos = findstr(~isnan(x), [1 1 1]);
if ~isempty(pos)
startPos = pos(1);
stopPos = startPos + 2;
% Find any cases where we have consecutive numbers in pos
if length(pos) > 1 && any(diff(pos) == 1)
% We have a contiguous section longer than 3 elements
% Find the NaNs
nans = find(isnan(x));
% Find the first NaN after pos(1), or the index of the last element
stopPos = nans(nans > startPos);
if ~isempty(stopPos)
stopPos = stopPos(1) - 1; % Don't want the NaN
else
stopPos = length(x);
end
end
end
x(startPos:stopPos)
這裏是用來提高有效性的邊界我的環路的圖像對於列:http://imgur.com/6i9Flt9(它很長,不會在評論中格式良好)。此外,y_A是我正在評估的點的數組,而step_A是一個向量,顯示每列給出3個點所需的增量數。 我不知道我理解你的findstr實現。爲什麼它會返回6你的情況和超過3個連續點是好的,這些是線性迴歸。 – TheMcCleaver
編輯的答案包括更多的解釋和稍微更全面的解決方案。 – wakjah