check if there are consecutive same values in a vector and if not, chagne that value to 0 in matlab

You can use the diff function to find the difference between consecutive elements in the vector. If two consecutive elements have a zero difference, it means they are the same. Here is an example code to replace the consecutive same values with zero:

main.m
v = [1 2 5 3 3 7 4 8];
diff_v = diff(v);
same_inds = find(diff_v == 0); % find indices of consecutive same values
for i = 1:length(same_inds)
    v(same_inds(i)+1) = 0; % set the second value in the consecutive same pair to zero
end
233 chars
7 lines

In the above code, we first calculate diff_v, which is a vector of differences between consecutive elements of v. We then find the indices of same_inds where the values of diff_v are zero. Finally, we loop through all same_inds and set the second value in the consecutive same pair to zero. In the above example code, the output vector v will be [1 2 5 3 0 7 4 8].

Note that this example code replaces only the second value in the consecutive same pair with zero. If you want to replace all consecutive same values with zero, you can modify the code accordingly.

related categories

gistlibby LogSnag