优化字符串的出现次数

时间:2012-06-30 19:43:09

标签: string matlab optimization vectorization

我必须计算单元格数组中包含某个字符串的频率。问题是代码是减慢它需要将近1秒才能做到这一点的方法。

    uniqueWordsSize = 6; % just a sample number
    wordsCounter = zeros(uniqueWordsSize, 1);
    uniqueWords = unique(words); % words is a cell-array

    for i = 1:uniqueWordsSize
        wordsCounter(i) = sum(strcmp(uniqueWords(i), words));
    end

我目前正在做的是将uniqueWords中的每个单词与单元格数组单词进行比较,并使用sum来计算strcmp返回的数组之和。

我希望有人可以帮助我优化它...... 1个单词,6个单词就太多了。

编辑:会员甚至更慢。

2 个答案:

答案 0 :(得分:3)

您可以使用unique的第三个输出和hist完全放弃循环:

words = {'a','b','c','a','a','c'}
[uniqueWords,~,wordOccurrenceIdx]=unique(words)
nUniqueWords = length(uniqueWords);
counts = hist(wordOccurrenceIdx,1:nUniqueWords)

uniqueWords = 
    'a'    'b'    'c'
wordOccurrenceIdx =
     1     2     3     1     1     3
counts =
     3     1     2

答案 1 :(得分:0)

没有使用明确的fors的棘手方法..

clc
close all
clear all

Paragraph=lower(fileread('Temp1.txt'));

AlphabetFlag=Paragraph>=97 & Paragraph<=122;  % finding alphabets

DelimFlag=find(AlphabetFlag==0); % considering non-alphabets delimiters
WordLength=[DelimFlag(1), diff(DelimFlag)];
Paragraph(DelimFlag)=[]; % setting delimiters to white space
Words=mat2cell(Paragraph, 1, WordLength-1); % cut the paragraph into words

[SortWords, Ia, Ic]=unique(Words);  %finding unique words and their subscript

Bincounts = histc(Ic,1:size(Ia, 1));%finding their occurence
[SortBincounts, IndBincounts]=sort(Bincounts, 'descend');% finding their frequency

FreqWords=SortWords(IndBincounts); % sorting words according to their frequency
FreqWords(1)=[];SortBincounts(1)=[]; % dealing with remaining white space

Freq=SortBincounts/sum(SortBincounts)*100; % frequency percentage

%% plot
NMostCommon=20;
disp(Freq(1:NMostCommon))
pie([Freq(1:NMostCommon); 100-sum(Freq(1:NMostCommon))], [FreqWords(1:NMostCommon), {'other words'}]);