check if value in a vector is the same as the one before and the one after, and if not ,change that value to 0 in matlab

You can iterate through each element of vector except the first and last element and check if they are equal to its adjacent elements or not. If they are not same, set the value to 0. Here is the code snippet.

main.m
for i = 2:length(vector)-1
    if vector(i) ~= vector(i-1) || vector(i) ~= vector(i+1)
        vector(i) = 0;
    end
end
122 chars
6 lines

This code will set the values in vector to 0 if it is not equal to its adjacent values.

Note that the first and last element of vector are not being checked as they do not have an adjacent element. So, it is assumed that they are already having the correct value.

related categories

gistlibby LogSnag