This solution takes an input vector 'v' and differentiates the indices of non-zero values in order to measure the distance between non-zero values. It then determines which distances are within a specified window 'd' and then loops through each of those groupings to calculate the maximum value within the groups and stores it in the output vector 'vNew'. If you have any trouble running the code or understanding parts of it, please leave a comment.
v = [0 0 0 2 0 3 0 0 0 0 4 0 4 0 0 0 0 0 0 0 5];
d = 3;
vNew = zeros(size(v));
notZeroSub = find(v ~= 0);
interDist = diff(notZeroSub);
isNear = [interDist <= d-1, false];
i = 1;
while i <= length(isNear)
nextFalseIdx = find(~isNear(i:end), 1) + i - 1;
inWindow = notZeroSub(i):notZeroSub(nextFalseIdx);
vNew(inWindow) = max(v(inWindow));
i = nextFalseIdx + 1;
end
table(v', vNew', 'VariableNames', {'Input', 'Output'})
Best Answer