Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 删除单词列表中的重复元素并计算重复次数_Matlab_Sorting - Fatal编程技术网

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

Matlab 删除单词列表中的重复元素并计算重复次数,matlab,sorting,Matlab,Sorting,这是我的代码,我尝试对一个单词数组进行排序,并调用排序后的数组“a”。 我试图使用while循环来比较a的相邻元素,当它被排序时,任何重复都应该彼此相邻。如果有重复的话,我就把这个词去掉,然后记下来。我不确定如何让我的输出显示每个排序的单词及其关联的计数在一起。谢谢你的帮助。 (myAsort是我已经做过的一个函数,它将单词按字母顺序排列) 例如,如果我输入myACsort({'cat','dog','cat'),我希望输出为: answer = 'cat' 'dog'

这是我的代码,我尝试对一个单词数组进行排序,并调用排序后的数组“a”。 我试图使用while循环来比较a的相邻元素,当它被排序时,任何重复都应该彼此相邻。如果有重复的话,我就把这个词去掉,然后记下来。我不确定如何让我的输出显示每个排序的单词及其关联的计数在一起。谢谢你的帮助。 (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
答案=
“猫”“狗”
计数:2计数:1
函数[answer]=myACsort(输入)
%此函数的无标题摘要如下所示
%这里有详细的解释
a=myAsort(输入);
n=长度(a);
i=1;
计数=1;
而(i和的通常组合将是我的建议:

>> 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(:)).'];
函数应答=myACsort(输入)
a=排序(输入);%sort对字符串的单元格数组进行操作
i=1;计数=1;
uwords=a(1);

而(i另一种方法:对字符串进行排序(变量
sortedStrs
),检测排序序列中每个相等字符串运行的结束(变量
ind
),并且很容易从中获得结果

strs = {'cat','dog','cat'}; %// data
n = numel(strs);
sortedStrs = sort(strs);
dif = arrayfun(@(n) ~strcmp(sortedStrs{n},sortedStrs{n-1}), 2:n);
ind = [ find(dif) n ];
result(1,:) = sortedStrs(ind);
result(2,:) = mat2cell([ind(1) diff(ind)],1,ones(1,numel(ind)));

+1我喜欢看到正确使用
而不是
:-)
有什么作用?我从来没有见过这种语法。@jerad,这是元素转换。没有点,这是关键。区别只在复杂的数据中起作用,但这是一种很好的做法。你得到你想要的答案了吗?