2011-09-26 81 views
1

我是matlab的新手。作爲更大問題的一部分,我需要在字符串數組中找到最大數量的字符串。java到matlab的轉換

由於我在java中有一些經驗,我已經用java編寫了部分代碼(只有當字符串數組中字符串的出現次數可以計算出來時,我纔可以根據這些值對這個hashmap進行排序並解壓縮)

int incr = 0; 
    String[] c = { "c1", "c2", "c3", "c1", "c2", "c2", "c2","c1","c2" }; 
    Map<String, Integer> classRegistry = new HashMap<String, Integer>(); 
    for (int i = 0; i < c.length; i++) { 
     String classes = c[i]; 
     if (!(classRegistry.containsKey(classes))) { 
      for (int j = i + 1; j < c.length; j++) { 
       if (classes.equals(c[j])) { 
        incr++; 
       } 
      } 
      classRegistry.put(classes, incr+1); 
      incr = 0; 
     } 
    } 

任何想法如何,我可以使用像MATLAB中的一個HashMap來計算陣列中的所有串出現的次數

感謝,

巴維亞

回答

2

MATLAB具有的功能TABULATE提供統計工具箱:

c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'}; 
t = tabulate(c) 
t = t(:,1:2) 

結果:

t = 
    'c1' [3] 
    'c2' [5] 
    'c3' [1] 

或者,您可以使用UNIQUEACCUMARRAY功能做同樣的:

c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'}; 
[classes,~,subs] = unique(c); 
counts = accumarray(subs(:),1); 

同樣的結果如前:

>> t = [classes(:) num2cell(counts)] 
t = 
    'c1' [3] 
    'c2' [5] 
    'c3' [1] 

然後找到發生的最多,使用的字符串:

>> [~,idx] = max(counts); 
>> classes(idx) 
ans = 
    'c2' 
+0

我使用了列表功能,很容易獲得解決方案。 – bhavs

1

你沒有指定你希望你的輸入和輸出數據類型如何,但我寫了這個快速腳本,你可能會發現有用。

c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'}; 
count = struct(); 
for ic=1:length(c) 
    field = c{ic}; 
    if isfield(count, field) 
     count = setfield(count, field, getfield(count, field) + 1); 
    else 
     count = setfield(count, field, 1); 
    end 
end 

這個特定c輸出將

count = 

    c1: 3 
    c2: 5 
    c3: 1 
0

既然你對Java的經驗,你可以只寫你的代碼的Java和MATLAB調用它。如果你決定走這條路線,This techdoc article應該可以幫助你開始。但它很可能是更有益的學習如何做,在M-腳本(參見jomb87的答案)

順便說一句,如果你把哈希表的另一個優點,你可以改善你的Java算法的性能:

for (int i = 0; i < c.length; i++) { 
     String classes = c[i]; 
     if (classRegistry.containsKey(classes)) { 
      classRegistry.put(classes, classRegistry.get(classes) + 1); 
     } else { 
      classRegistry.put(classes, 1); 
     } 
    }