how to check if there are two consecutive values the same in a vector and if there are not, set them to 0 in matlab

This can be done using a for loop as shown below:

main.m
v = [1 2 2 3 4 4 4 5];
for i = 1:length(v)-1
    if v(i) == v(i+1)
        % do something
    else
        v(i) = 0;
    end
end
129 chars
9 lines

In the above code we are looping over the vector v using a for loop. We start by checking if the current value in the vector matches the next value. If it matches, then we can perform some operation, otherwise we set the current value to 0.

This will replace all non-consecutive values with 0. In case you only want to remove the non-consecutive values, and keep the consecutive ones, you can replace the v(i) = 0 with v(i) = [], which will remove the element at that index.

Tags: vector, for-loop, conditional

related categories

gistlibby LogSnag