matlab - 删除单词列表中的重复元素并计算重复次数

标签 matlab sorting

这是我的代码,我正在尝试对单词数组进行排序,并调用排序后的数组“a”。 我正在尝试使用 while 循环来比较 a 的相邻元素,并且当它被排序时,任何重复都应该已经彼此相邻。如果有重复,我会删除单词 and 并将其计入计数。我不确定如何让我的输出显示每个排序的单词及其相关的计数。感谢您的任何帮助。 (myAsort 是我已经制作的一个函数,可以将单词按字母顺序排列) 例如,如果我输入 myACsort({'cat','dog','cat'),我希望输出为:

answer = 
    'cat'     'dog'
    count:2   count:1

function [ answer ]= myACsort( input )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
a = myAsort(input);
n = length(a);
i = 1;
count = 1;
while (i<=n)
    if isequal(a{i},a{i+1})
        a(i+1) = [];
        count = count+1;
    else
        count = 1;
        i=i+1;


    end

end



end

最佳答案

unique 的常用组合和 accumarray我的建议是:

>> strs = {'cat','dog','cat'};
>> [uStr,ia,ic] = unique(strs);
>> countCell = [uStr(:).'; num2cell(accumarray(ic,1)).']
countCell = 
    'cat'    'dog'
    [  2]    [  1]

仅供引用,您稍后可以通过 counts = [countCell{2,:}]; 提取计数。


如果您想在没有这些函数帮助的情况下完成此操作,您可以按如下方式修复 myACsort 函数:

function answer = myACsort(input)
a = sort(input); % sort operates on cell arrays of strings
i = 1; count = 1;
uwords = a(1);
while (i<numel(a))
    if i<numel(a) && isequal(a{i},a{i+1})
        a(i+1) = [];
        count(i) = count(i)+1;
    else
        i=i+1;
        count(i) = 1;
        uwords(i) = a(i); 
    end
end
answer = [uwords(:).'; num2cell(count(:)).'];

虽然数组增长效率不是很高。

关于matlab - 删除单词列表中的重复元素并计算重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051596/

相关文章:

matlab - 在 matlab 中为对数图选择不同的基数

c++ - 使用 OpenCV 计算协方差矩阵

c++ - 使用 Matlab Coder 将 Matlab m 文件转换为 C/C++ 代码,包括 mex 文件 (mxArray)

c++ - C++ 中的归并排序

c++ - 如何在 C++ 排序期间监视/显示进度

c++ - mex 编译时出现 GCC 版本警告

python - 查找由一组线创建的平面的所有分区

javascript - 对对象数组进行排序(输出数据但不按顺序)

c - 以两种方式实现快速排序算法但只接受一种?

algorithm - 查找与输入数组具有最大交集的数组的有效方法