Number of times two numbers appear together

1 view (last 30 days)
Hi,
I have an array A = [1 3 2 4 3 4 3 2 1 1 3 2 4 3 3 2].
How can I count the number of time the number 2 occurs after 1, the number of times the number 3 occurs after 1, and the number of times the number 4 occurs after 1?
Any help would be appreciated.
Thanks,
DB

Accepted Answer

Stephen23
Stephen23 on 10 Oct 2018
Edited: Stephen23 on 10 Oct 2018
>> A = [1,3,2,4,3,4,3,2,1,1,3,2,4,3,3,2];
Method one: basic indexing and nnz:
>> nnz(A(1:end-1)==1 & A(2:end)==2)
ans = 0
>> nnz(A(1:end-1)==1 & A(2:end)==3)
ans = 2
>> nnz(A(1:end-1)==1 & A(2:end)==4)
ans = 0
Method two: strfind:
>> nnz(strfind(char(A),char([1,2])))
ans = 0
>> nnz(strfind(char(A),char([1,3])))
ans = 2
>> nnz(strfind(char(A),char([1,4])))
ans = 0

More Answers (0)

Categories

Find more on Elementary Math 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!