AnnaSchumann
AnnaSchumann

Reputation: 1271

Tallying coincidences of numbers (Part 2) - MATLAB

Following on from: Tallying co-incidences of numbers in columns of a matrix - MATLAB

I was wondering how best to go about the same task when the data is processed differently. Starting with a matrix of:

A = 

201 202
203 204
201 203
201 203
205 201

I simply need a matrix that tallies the coincidence of each number from Column 1 to Column 2 i.e.

201   202

201 occurs with 202 once and so on (it ignores that 202 occurs with 201, removing duplicates). This is stored in a 2D matrix with min(A):max(A) running down both sides.

The desired output for the above example (A) would be:

   201 202 203 204 205
201 0   1   2   0   0
202 0   0   0   0   0
203 0   0   0   1   0
204 0   0   0   0   0
205 1   0   0   0   0

Upvotes: 1

Views: 86

Answers (1)

Divakar
Divakar

Reputation: 221664

See if this works for you -

A1 = A-min(A(:))+1 %// Get offsetted values

Aout = zeros(max(A1(:)))
%// For performance: Aout(max(A1(:)),max(A1(:)))=0; 
%// But for this performance trick to work, make sure Aout isnt defined before.
%// Source - http://undocumentedmatlab.com/blog/preallocation-performance

idx = sub2ind(size(Aout),A1(:,1),A1(:,2))
%// For performance: idx = (A1(:,2)-1)*size(Aout,1) + A1(:,1)

unqidx = unique(idx) %// get unique indices
Aout(unqidx) = histc(idx,unqidx) %// put counts of indices into their places

Sample run with an extra added row of input data -

>> A
A =
   201   202
   203   204
   201   203
   201   203
   205   201
   202   201
>> Aout
Aout =
     0     1     2     0     0
     1     0     0     0     0
     0     0     0     1     0
     0     0     0     0     0
     1     0     0     0     0

Upvotes: 2

Related Questions