1

假设您有一系列 X/Y 值,其中存在“间隙”......

resolution = 0.1;
x = [0:resolution:10 10.5:resolution:20];   % 4 missing values (10.1, 10.2, 10.3, 10.4)
y = ones(1, length(x));

您如何识别序列中的“间隙”并将其替换为某种类型的值(例如,将其替换为 0)?

我认为这可行,但我想知道是否有更好的方法。此外,此方法仅适用于 1 个间隙(而不是多个间隙)。我希望有一种更简单的方法……甚至可能是一种非循环方法。

xDiff = diff(x);
calcResolution = min(xDiff);   % Try to calculate original resolution
newY = y;
newX = x;

thresh = 0.000001;
for i=1:length(xDiff)
   % Check any time the difference is larger than our resolution...
   if (abs(xDiff(i) - calcResolution) > thresh)
       gapSize = (xDiff(i) / calcResolution) - 1;
       newY = [y(1:i) zeros(1, gapSize) y(i:end)];
       newX = [x(1:i) (x(i) + calcResolution):calcResolution:x(i+1) x((i+1):end)];
   end
end

% newX == 0:resolution:20
% newY == [1 1 1 1 1 1 1 ... 0 0 0 0 ... 1 1 1 1 1 1 1]
4

2 回答 2

1
%Assumes the most frequent difference is the resolution
calcResoultion = mode(diff(x));

%Create data set with no gaps
xMin = min(x);
xMax = max(x);
noGapData = [xMin:calcResolution:xMax];

%Create full length of y data
y = ones(1,length(noGapData));

%Round data to mitigate number precision issues from comment
noGapData = round(noGapData * 100) / 100;
x = round(x * 100) / 100;

%Find values in noGapData that are not in x
missingValues = setdiff(noGapData,x);

%Replace 1 with 0 at indicies of missing (gap) values
y(find(ismember(noGapData,missingValues))) = 0;

没有循环,并且适用于具有任意数量间隙的数据(假设间隙数小于序列中的数据点数,以确保mode(diff(x))返回正确的分辨率。

于 2013-11-13T22:37:21.733 回答
1

这应该可行,假设(如 DaveH)元素之间最常出现的差距是分辨率,而且它x是按递增顺序排列的。这不是很好的代码,我相信它可以改进,但至少(我认为)它有效

d=diff(x);
gapStart=find((d-mode(d))>1e-10);
gap=[x(gapStart);x(gapStart+1)];
gapLength=cumsum(diff(gap)/resolution);
xNew=0:resolution:max(x);
yNew=zeros(size(xNew));
yNew(1:gapStart(1))=y(1:gapStart(1));
for i=1:length(gapStart)-1
    yNew(gapStart(i)+gapLength(i)+1-i:gapLength(i)+gapStart(i+1)-i)=y(gapStart(i)+1:gapStart(i+1));
end
yNew(gapStart(end)+gapLength(end)-i:end)=y(gapStart(end)+1:end)
于 2013-11-13T23:10:09.457 回答