在matlab中找到最常用的单词

问题描述 投票:-1回答:2

我有一个如下矩阵:

temp=[1     1     6;
      1     2     6;
      1     3     7;
      1     4     1;
      2     1     1;
      2     2     2;
      2     3     5;
      2     4     6;
      3     1     4;
      3     2     3;
      3     3     5;
      3     4     7;];

第一列表示document_id,第二列表示word_id,第三列表示它在document_id中的出现。我想在整个文档中找到前3个单词的频率。而不是仅使用大量循环,在Matlab中执行此操作的更好方法是什么?

我有一个初步的想法:

sorted=sortrows(temp, 2)

我猜histcount或accumarray可以帮助我,但不知道如何?

matlab matrix
2个回答
1
投票

哇!这是我正在寻找的答案:

sortrows(splitapply(@sum, sorted(:, 3), findgroups(sorted(:, 2))), -1)
ans =

    17
    14
    11
    11

https://www.mathworks.com/help/matlab/ref/splitapply.html

** Update1:​​实际上不是。因为它没有告诉我第二列中的哪个word_id正在创建它

** Update2:虽然我可以获得最高频率的word_id,但我无法使用以下方法获得前3个频率的word_id:

>> [index, max_val] =max(splitapply(@sum, sorted(:, 3), findgroups(sorted(:, 2))))

index =

    17


max_val =

     3

正确的最终答案:

>> [frequencies, original_positions] = sort(splitapply(@sum, sorted(:, 3), findgroups(sorted(:, 2))), 'descend')

frequencies =

    17
    14
    11
    11


original_positions =

     3
     4
     1
     2

1
投票

如果您对使用accumarray的解决方案感兴趣(如您所料),那么您可以:

[Pos, ~, ind] = unique(temp(:,2));   %Finding unique word IDs (unsorted) 
freq = accumarray(ind, temp(:,3));   %Frequencies             (unsorted)

获得前3个。按降序对频率进行排序,并在前三个索引中提取值(或按升序排序,并在最后三个索引中提取值)。

PosFreq = sortrows([Pos freq], 2, 'descend');  %Sorting according to frequencies
Top3PosFreq = PosFreq(1:3,:);                  %Extracting top three frequencies

结果:

Top3PosFreq =

     3    17
     4    14
     1    11
© www.soinside.com 2019 - 2024. All rights reserved.