Counting how many times a number occured after a specific number

1 visualización (últimos 30 días)
Chad el 10 de Abr. de 2020
Respondida: AB WAHEED LONE el 14 de Dic. de 2021
Lets say I have a sequence of numbers ranging from 1 to 4, S = [ 3 2 2 4 3 1 ]. I want a 4x4 matrix which tells me how many times I went from say 3 to 2 or 4 to 1. It would look like this: M = [ 0 0 0 0; 0 1 0 1; 1 1 0 0; 0 0 1 0]. Sounds simple, but I'm out of thoughts. Thanks.
1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
darova el 10 de Abr. de 2020
Can you explain more? I don't understand

Iniciar sesión para comentar.

Kelly Kearney el 10 de Abr. de 2020
This is a good use case for accumarray:
S = [ 3 2 2 4 3 1];
[seq, ~, g] = unique([S(1:end-1)' S(2:end)'], 'rows');
n = accumarray(g, ones(size(g)));
M = zeros(4);
idx = sub2ind(size(M), seq(:,1), seq(:,2));
M(idx) = n;
3 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
Kelly Kearney el 10 de Abr. de 2020
That only works if there is only one instance of each sequence, though:
S = [ 3 2 2 4 3 1 3 2];
[seq, ~, g] = unique([S(1:end-1)' S(2:end)'], 'rows');
% Method 1
n = accumarray(g, 1);
M = zeros(4);
idx = sub2ind(size(M), seq(:,1), seq(:,2));
M(idx) = n
% Method 2
M2 = accumarray(seq, 1, [4 4])
% Check...
assert(isequal(M,M2))
Result:
M =
0 0 1 0
0 1 0 1
1 2 0 0
0 0 1 0
M2 =
0 0 1 0
0 1 0 1
1 1 0 0
0 0 1 0
Error using testsnippets (line 2638)
Assertion failed.
Kelly Kearney el 10 de Abr. de 2020
Though apparently the call to unique is unnecessary... possibly what you were suggesting?
S = [ 3 2 2 4 3 1 3 2];
accumarray([S(1:end-1)' S(2:end)'], 1)
ans =
0 0 1 0
0 1 0 1
1 2 0 0
0 0 1 0
I learned something new!

Iniciar sesión para comentar.

Más respuestas (2)

Andrei Bobrov el 10 de Abr. de 2020
accumarray(hankel(S(1:end-1),S(end-1:end)),1)
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

AB WAHEED LONE el 14 de Dic. de 2021
for example , S= [1 2 2 3 1;
1 3 1 3 4;
1 3 4 1 3;
1 3 4 1 3;
1 3 4 1 3];
When i tried to count the same ((1,1),(1,2),(1,3),(1,4),(2,2),(2,3), etc), it just creates the square matrix of max element size.
for example in case of first row X=[1 2 2 3 1], the size of output matrix is 3*3 ,which should have been 4*4.
could you comment on this.
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by