2014-02-26 63 views
2

这是我的代码,我尝试对单词数组进行排序,并调用排序后的数组'a'。 我想用一个while循环来比较a的相邻元素,因为它是排序的,所以任何重复应该已经是彼此相邻的。如果有重复,我删除这个词,然后把它记录下来。我不确定如何让我的输出结果一起显示每个排序字和相关的计数。感谢您的任何帮助。 (myAsort是我已经做了一个函数,把单词按字母顺序排列),如果我输入myACsort({“猫”,“狗”,“猫”),我所要的输出是 例如:删除单词列表中的重复元素并计算重复次数

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 
+0

您是否得到了您正在寻找的答案? – chappjc

回答

2

uniqueaccumarray通常的组合是我的建议:

>> 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(:)).']; 

虽然阵增长也不是很有效的。

+0

+1我喜欢''''正确使用而不是''':-) –

+0

'.''做了什么?我从来没有见过这种语法。 – jerad

+1

@jerad这是元素转置。没有圆点,就是[复共轭转置](http://www.mathworks.com/help/matlab/ref/ctranspose.html)。这种差异只对复杂数据非常重要,但这是一个很好的做法。 – chappjc

0

另一种方法:对字符串进行排序(变量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)));