【问题标题】:Count the duplicate values in an array [duplicate]计算数组中的重复值[重复]
【发布时间】:2015-06-01 19:40:52
【问题描述】:

有人可以帮我在 Matlab 中创建一个函数吗?我有一个包含 40 个元素的数组,其中一些元素是重复的。

我需要创建一个函数来计算数组中的重复值并像这样打印,即:

Number 21 repeats 4 time(s)
Number 25 repeats 1 time(s)
Number 40 repeats 3 time(s) etc.

提前谢谢你。我已经尝试了几个小时。

【问题讨论】:

  • 如果您添加之前尝试中的代码,我们可以以此为基础帮助您确定问题所在以及如何解决问题。
  • 嗨,我不知道该怎么做,所以你可以提供一个可以解决问题的示例数组
  • 签出this

标签: arrays matlab function


【解决方案1】:

您可以使用uniquehistc

x = [1 3.5 4 3.5 4 9 7 9 4 2]; %// example data
unique_values = unique(x(:));
counts = histc(x(:), unique_values);

这个例子的结果是:

unique_values.' =
    1.0000    2.0000    3.5000    4.0000    7.0000    9.0000
counts.' =
     1     1     2     3     1     2

或者使用uniqueaccumarray

x = [1 3.5 4 3.5 4 9 7 9 4 2]; %// example data
[unique_values, ~, labels] = unique(x(:));
counts = accumarray(labels, 1);

【讨论】:

    【解决方案2】:

    你可以试试这个:

    array = randi(40,1,40)
    array_labels = unique(array)
    % counter(length(array_labels))=0
    counter = zeros(1,length(array_labels))
    for j=1:length(array_labels)
        for i=1:40
            if array(i)==array_labels(j)
               counter(j) = counter(j) + 1;
            end
        end
    end
    counter
    final = horzcat(array_labels',counter')
    sum(counter)
    

    【讨论】:

    • 另外,另一个答案更好。如果没有必要,您应该尽量不要使用循环。另一个答案提供了一个更简洁有效的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2019-07-22
    • 2021-07-06
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多