【问题标题】:How count the number of repeated numbers between a range of natural numbers in an array如何计算数组中自然数范围之间的重复数字的数量
【发布时间】:2013-04-04 20:48:40
【问题描述】:

我有一个排序的(升序)数组

[1 1 1 1 1 1.2 1.6 2 2 2 2.4 2.4 2.4 2.6 3 3.5 3.6 3.8 3.9 4 4.3 4.3 4.6 5 5.02 6 7]

我想检查并打印每个“自然数”之间的重复数字的数量。

例如:

1到2之间:0(不重复)

在 2 和 3 之间:3 与 2.4 重复

3 到 4 之间:0

4 到 5 之间:2 与 4.3 重复

5 到 6 点之间:0

6 点到 7 点之间:0

MATLAB 中是否有任何函数可以执行此任务?

【问题讨论】:

    标签: arrays matlab repeat


    【解决方案1】:

    您可以使用tabulate,甚至不需要对数组进行排序。 然后只需使用逻辑条件选择适当的元素。例如:

    A=[1 1 1 1 1 1.2 1.6 2 2 2 2.4 2.4 2.4 2.6 3 3.5 3.6 3.8 3.9 4 4.3 4.3 4.6 5 5.02 6 7]
    M=tabulate(A)                  % get frequency table
    id1=mod(M(:,1),1)>0;           % get indices for non integer values
    id2=M(:,2)>1;                  % get indices for more than one occurrence
    idx=id1 & id2;                 % get indices that combines the two above
    ans=[M(idx,1) , M(idx,2)]      % show value , # of repeats
    
    ans =
        2.4000    3.0000
        4.3000    2.0000
    

    【讨论】:

      【解决方案2】:

      替代方法是使用histc。所以如果你的向量存储在一个 then

      h = histc(a,a); % count how many times the number is there, the a should be sorted
      natNumbers = (mod(a,1)==0) .* h;
      nonnatNum = (mod(a,1)>0).*h;
      indNN = find(natNumbers>0);
      indNNN = find(nonNatNumbers>1);
      resultIndex = sort([indNN indNNN]);
      result = [a(resultIndex);h(resultIndex)]
      

      然后您可以通过检查自然数之间是否有任何数字来处理结果矩阵

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 2020-02-20
        相关资源
        最近更新 更多