恐怕我的回答对你来说太晚了,但也许未来有类似问题的读者可以从中受益。
一般来说,您的问题需要cluster analysis。不过,对于您的实际问题,也许有一个更简单的解决方案。这是我的方法:
- 首先,
sort 输入 A。
- 为了找到区分“类内”和“类间”元素的标准,我使用
diff 计算A 的相邻元素之间的差异。
- 然后,我计算所有这些差异的
median。
- 最后,我
find 为所有差异的索引,它们大于或等于中位数的三倍,最小差异为1。 (根据实际数据,这可能会被修改,例如改用mean。)这些是索引,您必须在其中“拆分”(排序的)输入。
- 最后,我为每个“子矩阵”设置了两个带有开始和结束索引的向量,以使用this 方法,使用
arrayfun 来获得一个包含所有所需“子矩阵”的元胞数组。
现在,代码来了:
% Sort input, and calculate differences between adjacent elements
AA = sort(A);
d = diff(AA);
% Calculate median over all differences
m = median(d);
% Find indices with "significantly higher difference",
% e.g. greater or equal than three times the median
% (minimum difference should be 1)
idx = find(d >= max(1, 3 * m));
% Set up proper start and end indices
start_idx = [1 idx+1];
end_idx = [idx numel(A)];
% Generate cell array with desired vectors
out = arrayfun(@(x, y) AA(x:y), start_idx, end_idx, 'UniformOutput', false)
由于可能的向量数量未知,我想不出将这些“解包”为单个变量的方法。
一些测试:
A =
1 2 3 6 7 8
out =
{
[1,1] =
1 2 3
[1,2] =
6 7 8
}
A =
5 11 6 4 4 3 12 30 33 32 12
out =
{
[1,1] =
3 4 4 5 6
[1,2] =
11 12 12
[1,3] =
30 32 33
}
A =
1 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 3
out =
{
[1,1] =
1 1 1 1 1 1 1
[1,2] =
2 2 2 2 2 2
[1,3] =
3 3 3 3 3 3 3
}
希望有帮助!