Calculate how often a 1 turns into a 0 or 1, and vice versa
1 view (last 30 days)
Show older comments
Hi all,
I've got some data that characterize two possible states and stored in an array (1s and 0s), and there are 8 repetitions per recording. The data look something like this:
a = [1 1 1 0 1 0 0 1; 1 1 0 1 1 0 1 0];
Where I perform 8 experimental repetitions (2 shown).
I've got a hunch that a 1 is followed by a 0 more often than by a 1, and want to quantify that.
Let's say a 1 has a 65% chance of being followed by a 1, and a 35% chance of being followed by a 0. Additionally, a 0 might have a 90% chance of being followed by a 1, and a 10% chance of being followed by a 0.
What's an efficient way to ask MATLAB if this is actually the case?
So far, I'm thinking maybe use strfind with 4 repetitions, 1 for each possibility, like:
strfind(a,[1,1]);
strfind(a,[1,0]);
strfind(a,[0,1]);
strfind(a,[0,0]);
Thanks for your thoughts.
0 Comments
Answers (4)
Matt J
on 13 Aug 2014
Edited: Matt J
on 13 Aug 2014
bayes=@(u,v) 100*sum(u&v,2)/sum(v,2); %conditional prob as percent
first1=a(:,1:end-1);
next1=a(:,2:end);
first0=~first1;
next0=~next1;
out_1_1 = bayes( first1 & next1, first1 );
out_0_0 = bayes( first0 & next0, first0 );
out_1_0 = bayes( first1 & next0, first1 );
out_0_1 = bayes( first0 & next1, first0 );
Ahmet Cecen
on 13 Aug 2014
Edited: Ahmet Cecen
on 13 Aug 2014
check1=(a+circshift(a,[-1 0]));
check2=(a-circshift(a,[-1 0]));
check1==0 % is 0's followed by 0's
check1==2 % is 1's followed by 1's
check2==1 % is 1's followed by 0's
check2==-1 % is 0's followed by 1's
Very fast, elegant, no explicit loops. You will have to ignore the values at the last column, since that doesn't make sense anyways.
2 Comments
Matt J
on 13 Aug 2014
no explicit loops
You could avoid implicit loops too by doing
check1=conv2(a,[1,1],'valid');
check2=-diff(a,1,2);
Azzi Abdelmalek
on 13 Aug 2014
a = [1 1 1 0 1 0 0 1; 1 1 0 1 1 0 1 0]
for k=1:size(a,1)
out{1,k}=numel(strfind(a(k,:),[1,1]))
out{2,k}=numel(strfind(a(k,:),[1,0]))
out{3,k}=numel(strfind(a(k,:),[0,1]))
out{4,k}=numel(strfind(a(k,:),[0,0]))
end
0 Comments
Andrei Bobrov
on 13 Aug 2014
Edited: Andrei Bobrov
on 13 Aug 2014
a = [1 1 1 0 1 0 0 1; 1 1 0 1 1 0 1 0];
n = size(a)-[0 1];
da = diff(a,1,2);
t = [ones(n(1),1) da] == 0;
[r,~] = find(t);
da2 = a.*t;
da2 = da2(t);
out_1_1 = accumarray(r,da2 == 1)/n(2)*100;
out_0_0 = accumarray(r,da2 == 0)/n(2)*100;
out_1_0 = sum(da == -1,2)/n(2)*100;
out_0_1 = sum(da == 1,2)/n(2)*100;
with strfind
z = cellnum([0 0; 1 1; 0 1; 1 0],2)';
n = [size(a,1),numel(z)];
out = zeros(n);
for ii = 1:n
out(ii,:) = cellfun(@(x)numel(strfind(a(ii,:),x))/(n(2)-1)*100,z);
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!