1

我必须计算某个字符串包含在单元格数组中的频率。问题是代码是减慢它需要将近 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 返回的数组的总和。

我希望有人可以帮助我优化它.... 6 个单词的 1 秒实在是太多了。

编辑: ismember 甚至更慢。

4

2 回答 2

3

您可以使用uniquewith的第三个输出完全删除循环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
于 2012-06-30T20:13:49.710 回答
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'}]);
于 2014-03-03T09:12:26.677 回答