1

I have 10 bins, and each bin contains a specific number of observations, e.g.:

a = [0,0,1,0,0,2,0,0,0,2]

I'd like to subsequently tally how many times any given pair of (non-zero) bins co-occur - based on the number of observations.

Given the above example, bin#3 = 1, bin#6 = 2 and bin#10 = 2.

This means that bin 3 and 6 co-occurred once, bin 3 and 10 co-occurred once, and bin 6 and 10 co-occurred twice (the minimum value of the pair is taken).

My desired output is a full matrix, listing every possible bin combination (columns 1-2) and the tally of what was observed (column 3):

1   2   0
1   3   0
1   4   0
1   5   0
1   6   0
1   7   0
1   8   0
1   9   0
1   10  0
2   3   0
2   4   0
2   5   0
2   6   0
2   7   0
2   8   0
2   9   0
2   10  0
3   4   0
3   5   0
3   6   1
3   7   0
3   8   0
3   9   0
3   10  1
4   5   0
4   6   0
4   7   0
4   8   0
4   9   0
4   10  0
5   6   0
5   7   0
5   8   0
5   9   0
5   10  0
6   7   0
6   8   0
6   9   0
6   10  2
7   8   0
7   9   0
7   10  0
8   9   0
8   10  0
9   10  0

Is there a short and/or fast way of doing this?

AnnaSchumann
  • 1,261
  • 10
  • 22

2 Answers2

1

Try this.

bin_output = [....];
bin_matrix = [0,0,1,0,0,2,0,0,0,2];
bin_nonzero = find(bin_matrix);
for j = 1:length(bin_nonzero);
    if isequal(j,length(bin_nonzero))
        break;
    end
    for k = (j+1):(length(bin_nonzero))
        for m = 1:length(bin_output)
            if isequal(bin_output(m,1),j) && isequal(bin_output(m,2),k)
                bin_output(m,3) = bin_output(m,3) + min([bin_matrix(1,bin_nonzero(1,j)),bin_matrix(1,bin_nonzero(1,k))]);
            end
        end
    end
end
medicine_man
  • 321
  • 3
  • 15
1

You can get all combinations of the bin numbers in many ways. I'll use combvec for ease.

Then it's relatively simple to vectorise this using min...

a = [0,0,1,0,0,2,0,0,0,2];

n = 1:numel(a);
% Use unique and sort to get rid of duplicate pairs when order doesn't matter
M = unique( sort( combvec( n, n ).', 2 ), 'rows' ); 
% Get rid of rows where columns 1 and 2 are equal
M( M(:,1) == M(:,2), : ) = [];
% Get the overlap count for bins
M( :, 3 ) = min( a(M), [], 2 );
Wolfie
  • 27,562
  • 7
  • 28
  • 55