check if there are consecutive same values in a vector in matlab

You can use the diff function to get the difference between consecutive elements of the vector and then check if any of the differences equal zero.

Here's an example code snippet:

main.m
v = [1 2 2 3 4 4 4 5];
consecutive = any(diff(v) == 0);
56 chars
3 lines

In this example, the variable v is a vector with consecutive same values. The diff(v) function returns a new vector where each element is the difference between consecutive elements in v, thus resulting with [1 0 1 1 0 0 1]. Then the diff(v) == 0 expression is a logical vector where each element is true if the corresponding element in the diff vector is zero. Finally, the any function returns true if at least one of the elements in the logical vector is true, indicating that there are consecutive same values in the vector.

Note that this code snippet only checks if there are consecutive same values and doesn't provide the indices or the number of repeats. If you need more information, you can modify the code accordingly.

gistlibby LogSnag