计算符号的重合(第2部分) - MATLAB

时间:2014-11-05 16:48:18

标签: matlab

继续:Tallying co-incidences of numbers in columns of a matrix - MATLAB

我想知道在以不同方式处理数据时如何最好地执行相同的任务。从矩阵开始:

A = 

201 202
203 204
201 203
201 203
205 201

我只需要一个矩阵来计算从第1列到第2列的每个数字的重合,即

201   202

201一次发生202次,依此类推(它忽略202发生201,删除重复)。这存储在2D矩阵中,其中min(A):max(A)向下运行。

上述示例(A)的所需输出为:

   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

1 个答案:

答案 0 :(得分:2)

看看这是否适合你 -

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

使用额外添加的输入数据行运行示例 -

>> 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