Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find indices where array changes

Tags:

matlab

I have an array something like this:

[0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 ... ]

I want to find the indices where 0 changes to 1 and 1 changes to 0. So for the following array:

changes = [5 10 14 17 20]

I know how to use find and a vector predicate expression like find(A > 3) to search for simpler conditions, but this has me stuck. I could write a big loop and do it, but I feel there must be something built-in or otherwise easier to achieve the same thing.

like image 689
Zane Kaminski Avatar asked Feb 20 '26 18:02

Zane Kaminski


2 Answers

A very simple approach which works with all values as start would be:

changes = find(diff(value))+1;

This will also return the expected result changes = [5 10 14 17 20].

like image 195
Dennis Klopfer Avatar answered Feb 23 '26 12:02

Dennis Klopfer


Figured out a solution.

find(circshift(value, [0, 1]) ~= value)

For my application, the array is guaranteed to begin and end with 0s, otherwise it will not work properly.

like image 35
Zane Kaminski Avatar answered Feb 23 '26 11:02

Zane Kaminski