Thread Subject: Count state switches in a vector?

Subject: Count state switches in a vector?

From: Ian Clarkson

Date: 9 Oct, 2008 13:53:13

Message: 1 of 3

Hi there,

I'm trying to find a smart (read: vectorized) way to count "state switches" in a vector. What I mean is, the number of times a vector switches between 0 and 1:

[0 1 0] -> 2
[1 0 1] -> 2
[0 0 1] -> 1
[0 0 0 1 1 0 0 1 1] -> 3
[1 1 1 1 1 1 1 1 0] -> 1

The solution only really needs to take a vector of length 32, and it will always be a value of either 0 or 1. I can obviously do this in a loop, but I was wondering if there was some clever function I could use to do this for a really big set of these vectors. Maybe something about a cumulative summation or something?

Thanks!

Subject: Count state switches in a vector?

From: Walter Roberson

Date: 9 Oct, 2008 16:43:45

Message: 2 of 3

Ian Clarkson wrote:
 
> I'm trying to find a smart (read: vectorized) way to count "state switches" in a vector.

> [0 0 0 1 1 0 0 1 1] -> 3

> The solution only really needs to take a vector of length 32, and it will always be a value
> of either 0 or 1.

sum(abs(diff([0 0 0 1 1 0 0 1 1])))

OR

>> A = [0 0 0 1 1 0 0 1 1];
>> sum(A(1:end-1) ~= A(2:end))

Subject: Count state switches in a vector?

From: Walter Roberson

Date: 9 Oct, 2008 16:44:53

Message: 3 of 3

Walter Roberson wrote:
> Ian Clarkson wrote:
>> I'm trying to find a smart (read: vectorized) way to count "state
>> switches" in a vector.

>>> A = [0 0 0 1 1 0 0 1 1];
>>> sum(A(1:end-1) ~= A(2:end))

Or, since you are only using 0 and 1,

sum(xor(A(1:end-1),A(2:end)))

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Contact us at files@mathworks.com