【问题标题】:Cluster analysis on a 1D vector一维向量的聚类分析
【发布时间】:2021-12-29 18:23:33
【问题描述】:

考虑以下数据:

A = [-1 -1 -1 0 1 -1 -1 0 0 1 1 1 1 -1 1 0 1];

如何计算A(相似邻居)中簇的大小和出现频率,最好使用MATLAB内置命令?

结果应该是这样的

s_plus = [1 2 3 4 5 ; 3 0 0 1 0]'; % accounts (1,1,1,1) and (1),(1),(1) which appear in A 
s_zero = [1 2 3 4 5 ; 2 1 0 0 0]'; % accounts (0,0) and (0),(0) which appear in A
s_mins = [1 2 3 4 5 ; 1 1 1 0 0]'; % accounts (-1), (-1,-1) , and (-1,-1,-1)) which appear in A

上面第一列表示聚类大小,第二列表示出现频率。

【问题讨论】:

  • 要找到具有大小的集群,您应该可以使用this solution;只需对所有 unique(A) 元素进行循环即可找到各种值。

标签: arrays matlab cluster-analysis


【解决方案1】:

您可以使用run length encoding 将输入数组转换为两个数组

  1. 组的值(或相等值的“运行”)
  2. 该组中的元素数

然后您可以通过检查两个条件何时为真将其转换为您想要的输出

  1. values 数组与您想要的值匹配 (-1,0,1)
  2. 组大小匹配1..5

这可能听起来有点棘手,但它只有几行代码,即使是大型数组也应该相对较快,因为输出是从小于输入数组的“编码”数组计算出来的。

代码如下,详情见cmets:

A = [-1 -1 -1 0 1 -1 -1 0 0 1 1 1 1 -1 1 0 1]; % Example input

% Run length encoding step
idx = [ find( A(1:end-1) ~= A(2:end) ), numel(A) ]; % Find group start points
count = diff([0, idx]); % Find number of elements in each group
val = A( idx );         % Get value of each group
% Helper function to go from "val" and "count" to desired output format
% by checking value = target and group size matches 1 to 5, counting matching groups. 
f = @(v) sum(val==v & count==(1:5).',2).';
% Create outputs
s_plus = f(1);  % = [3 0 0 1 0]
s_zero = f(0);  % = [2 1 0 0 0]
s_mins = f(-1); % = [1 1 1 0 0]

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 2017-08-20
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多