Replacing values in vector segments with highest value

Hi,
I have a vector [1x100] with positive numbers or zeroes. In example: [0 0 0 2 0 3 0 0 0 0 4 0 4 0 0 0 0 0 0 0 5.....].
The wanted result is same length vector which checks condition: if numbers > 0 occur in 3 consequent places, replace that segment with highest number in that segment. This means that my example vector should look like this: [0 0 0 3 3 3 0 0 0 0 4 4 4 0 0 0 0 0 0 0 5....]

3 Comments

And what if you have:
A = [ 1 0 2 0 3 0 4 0 5 0 6 ]?
Is the expected answer:
B = [ 6 6 6 6 6 6 6 6 6 6 6 ]?
or
B = [ 2 2 3 3 4 4 5 5 6 6 6 ]?
But nowhere in your example are there 3 consecutive numbers greater than zero.
Judging from your example, you're searching for any number greater than zero within 3 indices from another number greater than zero.
What would be the output for this number?
[0 0 0 2 0 3 0 5 0 6 4 0 4 0 0 0 0 0 0 0 5]
If I have A = [ 1 0 2 0 3 0 4 0 5 0 6 ] vector then expected answer should be B = [ 6 6 6 6 6 6 6 6 6 6 6 ].
Adam Danz - you are right, I made mistake in description. Im searching within next three indices. Thus, the answer should be [0 0 0 6 6 6 6 6 6 6 6 6 6 0 0 0 0 0 0 0 5].

Sign in to comment.

 Accepted Answer

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.
% Input vector (row or column)
v = [0 0 0 2 0 3 0 0 0 0 4 0 4 0 0 0 0 0 0 0 5];
% specify window size
d = 3; %window size. Example: [2 0 3] has window size of 3
% determine which elements are 'near' based on window size
vNew = zeros(size(v)); %allocate the output variable
notZeroSub = find(v ~= 0); %get the index of each non-zero element
interDist = diff(notZeroSub); %distance between each non-zero
isNear = [interDist <= d-1, false]; %identify which distances are within the window specified
i = 1; %start from the first index value
% Slide window across the 'isNear' vector and replace values from input with local maximums
while i <= length(isNear)
% find next 'false' which marks a group-speration
nextFalseIdx = find(~isNear(i:end), 1) + i - 1;
% list all indices that are within the current window
inWindow = notZeroSub(i):notZeroSub(nextFalseIdx);
% Set all values within window to max value
vNew(inWindow) = max(v(inWindow));
% increment i
i = nextFalseIdx + 1;
end
% Compare input/output
table(v', vNew', 'VariableNames', {'Input', 'Output'})

More Answers (0)

Products

Release

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!