Arrays 按顺序替换间隙中缺少的值

Arrays 按顺序替换间隙中缺少的值,arrays,matlab,Arrays,Matlab,假设您有一个X/Y值序列,其中有一个“间隙” 如何识别序列中的“间隙”,并用某种类型的值替换它(例如,用0替换) 我认为这是可行的,但我想知道是否有更好的方法。此外,此方法仅适用于1个间隙(而不是多个间隙)。我希望有一个更简单的方法…甚至可能是一个非循环方法 xDiff = diff(x); calcResolution = min(xDiff); % Try to calculate original resolution newY = y; newX = x; thresh = 0.0

假设您有一个X/Y值序列,其中有一个“间隙”

如何识别序列中的“间隙”,并用某种类型的值替换它(例如,用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]

没有循环,并且对任何间隙量的数据都有效(假设间隙数小于序列中的数据点数,以确保
模式(diff(x))
返回正确的分辨率。

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


这似乎不起作用,
missingValues
返回除0以外的
noGapData
的所有值。可能是数字精度问题,我需要进一步调查。文档看起来像
missingValues
应该只包含“间隙”值。@David对我的原始答案是正确的。我测试了这段代码。\n现在,通过对数据进行四舍五入,它确实将[10.1,10.2,10.3,10.4]识别为缺失值当存在间隙时,您如何定义缺失多少值?步骤应该是什么?@LuisMendo好问题。我需要计算步骤。我一直在使用diff()中的最小值,但我也喜欢使用下面答案中的
mode()
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]
%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;
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)