汇总矩阵列中数字的共同概率-MATLAB [英] Tallying co-incidences of numbers in columns of a matrix - MATLAB
问题描述
我有一个(A)矩阵(实际上更大):
I have a matrix (A) in the form of (much larger in reality):
205 204 201
202 208 202
我如何才能在列与列之间计算数字的重合度,然后将其输出到矩阵中?
How can I tally the co-incidence of numbers on a column-by-column basis and then output this to a matrix?
我希望最终矩阵从min(A):max(A)(或能够指定特定范围)遍历顶部和底部,并使其与数字中的共同点相符每列.使用上面的示例:
I'd want the final matrix to run from min(A):max(A) (or be able to specify a specific range) across the top and down the side and for it to tally co-incidences of numbers in each column. Using the above example:
200 201 202 203 204 205 206 207 208
200 0 0 0 0 0 0 0 0 0
201 0 0 1 0 0 0 0 0 0
202 0 0 0 0 0 1 0 0 0
203 0 0 0 0 0 0 0 0 0
204 0 0 0 0 0 0 0 0 1
205 0 0 0 0 0 0 0 0 0
206 0 0 0 0 0 0 0 0 0
207 0 0 0 0 0 0 0 0 0
208 0 0 0 0 0 0 0 0 0
(不需要矩阵标签)
两个要点:计数必须是不可重复的,并且应按数字顺序进行.例如,包含以下内容的列:
Two important points: The tallying needs to be non-duplicating and occur in numerical order. For example a column containing:
205
202
将其与202一起出现在205(如上面的矩阵所示)中,而不是205与202一起出现-互为倒数.在决定使用哪个数字作为参考时,它应该是最小的.
Will tally this as a 202 occurring with 205 (as shown in the above matrix) but NOT 205 with 202 - the duplicate reciprocal. When deciding what number to use as the reference, it should be the smallest.
推荐答案
让您的数据和所需范围定义为
Let your data and desired range be defined as
A = [ 205 204 201
202 208 202 ]; %// data. Two-row matrix
limits = [200 208]; %// desired range. It needn't include all values of A
然后
lim1 = limits(1)-1;
s = limits(2)-lim1;
cols = all((A>=limits(1)) & (A<=limits(2)), 1);
B = sort(A(:,cols), 1, 'descend')-lim1;
R = full(sparse(B(2,:), B(1,:), 1, s, s));
给予
R =
0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
或者,您可以省去sort
并使用矩阵加法后跟triu
来获得相同的结果(可能更快):
Alternatively, you can dispense with sort
and use matrix addition followed by triu
to obtain the same result (possibly faster):
lim1 = limits(1)-1;
s = limits(2)-lim1;
cols = all( (A>=limits(1)) & (A<=limits(2)) , 1);
R = full(sparse(A(2,cols)-lim1, A(1,cols)-lim1, 1, s, s));
R = triu(R + R.');
这两种方法都可以处理重复的列(直至排序),从而正确地增加其计数.例如,
Both approaches handle repeated columns (up to sorting), correctly increasing their tally. For example,
A = [205 204 201
201 208 205]
给予
R =
0 0 0 0 0 0 0 0 0
0 0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
这篇关于汇总矩阵列中数字的共同概率-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!