MATLAB: Calculate the frequency of element in a matrix

frequencymatrix

matrix = [1 1 1 1 4 5 5 7 14 14 14 14 14 15 15 15 17 17 ; 2 6 7 7 7 2 3 5 2 3 4 5 6 3 4 4 3 6 ; 7 7 5 7 6 3 2 5 6 6 7 6 3 3 2 5 5 5 ; 0 0 1 0 0 1 0 1 0 0 0 0 1 1 1 1 1 1]
I don't know how i can calculate how many times a number appears in the first row and at the same time calculate how many times a one appears in the fourth row when the element in the first row remains the same. For example my desired output would be:
matrix2 = [1 4 5 7 14 15 17 ;
4 1 2 1 5 3 2 ;
1 0 1 1 1 3 2]

Best Answer

matrix1 = [1 1 1 1 4 5 5 7 14 14 14 14 14 15 15 15 17 17 ;
2 6 7 7 7 2 3 5 2 3 4 5 6 3 4 4 3 6 ;
7 7 5 7 6 3 2 5 6 6 7 6 3 3 2 5 5 5 ;
0 0 1 0 0 1 0 1 0 0 0 0 1 1 1 1 1 1];
[a,~,c] = unique(matrix1(1,:));
[jj,ii] = ndgrid(c,1:2);
out = [a;accumarray([ii(:),jj(:)],[ones(size(matrix1,2),1);matrix1(4,:)'])];