Path: news.mathworks.com!not-for-mail
From: "Steve Amphlett" <Firstname.Lastname@Where-I-Work.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Number of changes in a value
Date: Tue, 9 Dec 2008 19:17:04 +0000 (UTC)
Organization: Ricardo UK Ltd
Lines: 33
Message-ID: <ghmg7g$ic6$1@fred.mathworks.com>
References: <ghmadq$egh$1@fred.mathworks.com> <ghmcfe$gq8$1@fred.mathworks.com> <y9z%k.777$Ir1.624@newsfe05.iad>
Reply-To: "Steve Amphlett" <Firstname.Lastname@Where-I-Work.com>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1228850224 18822 172.30.248.38 (9 Dec 2008 19:17:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 9 Dec 2008 19:17:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 43398
Xref: news.mathworks.com comp.soft-sys.matlab:505920


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).