如何收集元素之间具有相同长度的数组X的索引

时间:2014-07-15 10:13:52

标签: arrays matlab

我正在尝试创建一个数组Z,其中包含数组X中两个元素之间最常出现的差异的索引。因此,如果X中两个元素之间最常出现的差异为3,那么我将获得所有索引X与阵列Z有区别。

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6];
ct = 0;
difference_x = diff(x);
unique_x = unique(difference_x);
for i = 1:length(unique_x)
    for j = 1:length(x)
           space_between_elements = abs(x(i)-x(i+1));
           if space_between_elements  == difference_x
                ct = ct + 1;
                space_set(i,ct) = j;
           end
     end
end

我不希望X的索引包含与此代码最常见的差异。

1 个答案:

答案 0 :(得分:0)

您希望找到有多少独特差异,其中包含"差异"以绝对价值的意义解释 ;并且还找到每次差异发生的次数

您可以按照以下方式执行此操作:

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
difference_x = abs(diff(x));
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

然而,由于有限的精度,比较唯一性(或相等)的实数是problematic。您应该使用容差来声明两个值为"等于":

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
tol = 1e-6; %// tolerance
difference_x = abs(diff(x));
difference_x = round(difference_x/tol)*tol; %// apply tolerance
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

使用您的示例x,第二种方法提供

>> unique_x
unique_x =
         0    0.1000    0.2000    0.3000
>> counts
counts =
     1     4     3     2