这是我的代码,我正在尝试对单词数组进行排序,并调用排序后的数组“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/