2014-02-26 64 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)));