Borrar filtros
Borrar filtros

How to count the number of occurrences of each pair in a cell?

3 visualizaciones (últimos 30 días)
Suppose I have a cell array
C = {[1; 2; 3]; [1; 2; 3; 4]; [1; 2]};
c{:}
ans =
1
2
3
ans =
1
2
3
4
ans=
1
2
% where any digit won't repeat in the individual cell.
I need to find out the number of occurrences of each pair. Expected output:
Pair(1,2) = 3 occurences;
Pair(1,3) = 0;
Pair(1,4) = 0;
Pair(2,1) = 0;
Pair(2,3) = 2;
Pair(2,4) = 0;
Pair(3,1) = 0;
Pair(3,2) = 0;
Pair(3,4) = 1;
How can I find it?
  2 comentarios
Rik
Rik el 30 de Oct. de 2018
What code have you tried so far? It looks like there is a simple, naive approach with some loops that would solve it (not sure if there are some tricks you can pull to speed it up substantially).
Md Shahidullah Kawsar
Md Shahidullah Kawsar el 31 de Oct. de 2018
Editada: Md Shahidullah Kawsar el 31 de Oct. de 2018
I was trying this code for the array A = [1 2 3; 2 3 1; 2 1 3]
for n = 2:3
[j,i]=ind2sub(fliplr(size(A)), strfind(reshape(A.',1,[]),[1 n]).');
C = [i,j];
d = numel(C(j));
T9 = table(1, n, d)
end
but it has 2 problems: (1) error occurs when the second row ends with 1 and the third row begins with 2. (2) for cell array, this code doesn't work

Iniciar sesión para comentar.

Respuesta aceptada

Akira Agata
Akira Agata el 31 de Oct. de 2018
Editada: Akira Agata el 31 de Oct. de 2018
I think one possible way would be like this:
c = {[1; 2; 3]; [1; 2; 3; 4]; [1; 2]};
Pair = [repelem((1:4)',4,1),repmat((1:4)',4,1)];
Count = zeros(size(allPair,1),1);
for kk = 1:numel(c)
d = [c{kk}(1:end-1),c{kk}(2:end)];
[~,lo] = ismember(d,Pair,'rows');
Count = Count + (histcounts(lo,1:size(Pair,1)+1))';
end
T = table(Pair,Count);
The output is:
>> T
T =
16×2 table
Pair Count
______ _____
1 1 0
1 2 3
1 3 0
1 4 0
2 1 0
2 2 0
2 3 2
2 4 0
3 1 0
3 2 0
3 3 0
3 4 1
4 1 0
4 2 0
4 3 0
4 4 0

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays 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