Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Number of changes in a value
Date: Wed, 10 Dec 2008 10:29:02 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 46
Message-ID: <gho5le$9s2$1@fred.mathworks.com>
References: <ghmadq$egh$1@fred.mathworks.com> <ghmcfe$gq8$1@fred.mathworks.com> <y9z%k.777$Ir1.624@newsfe05.iad> <ghmg7g$ic6$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1228904942 10114 172.30.248.35 (10 Dec 2008 10:29:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 10 Dec 2008 10:29:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:506064


"Steve Amphlett" <Firstname.Lastname@Where-I-Work.com> wrote in message <ghmg7g$ic6$1@fred.mathworks.com>...
> Walter Roberson <roberson@hushmail.com> wrote in message <y9z%k.777$Ir1.624@newsfe05.iad>...
> > Roger Stafford wrote:
> > > "anoop Sivasankaran" <anooppgd@gmail.com> wrote in message <ghmadq$egh$1@fred.mathworks.com>...
> > 
> > >> Now I need to find number of changes. i.e I need to find how many changes from 1 to 2, 1 to 3,
> > >> 1 to 4, 2 to 1, 2 to 3 etc. 
> > 
> > > sum(diff(data)~=0)
> > 
> > Hmmm, my interpretation was that Anoop needs the counts for the cases individually, but
> > certainly that isn't clear.
> > 
> > Interesting, your formulation was the fastest of the several I tried
> > at about 0.15 seconds; several variants came in about 0.16 seconds, and
> > sum(data(1:end-1)~=data(2:end)) was about 0.31 seconds
> > 
> > The graycomatrix that I suggested in a posting above takes about 4 seconds
> > to produce the full 4 x 4 table.
> > 
> > And then there is:
> > 
> > [A,B] = meshgrid(1:4,1:4);
> > arrayfun(@(a,b) sum(foo(1:end-1)==a&foo(2:end)==b), A,B)
> > which takes about 6 seconds for the arrayfun
> > 
> > I couldn't seem to formulate the equivalent in bsxfun.
> 
> This looks like a problem for sparse() to solve .  Each pair of consecutive states (values) could be indices into a sparse 2D array that gets fed with ones and adds them up.  Not having ML at home, I thought I'd at least share this idea so that someone could maybe finish it off.
> 
> % Excuse syntax, probably wrong, but the right idea
> x=sparse(data(1:end-1),data(2:end),ones(length(data)-1),1);
> 
> ... or something along those lines.  Then zero the diagonal.  The result would be a 4x4 sparse matrix which each (row,col) containing the number of transitions from (row) to (col).

Indeed, sparse is the way to go:

V = [1 2 3 2 4 1 4 2 3 1 4 2 3 2 1 3 2 4 3 2 3 4 2 3 4 1 2 1 2 1] ;
A = full(sparse(V(1:end-1),V(2:end),1))

so that A(i,j) holds the number of changes from i to j

Jos