【问题标题】:Comparing strings in cell arrays比较元胞数组中的字符串
【发布时间】:2013-11-08 23:18:35
【问题描述】:

我正在尝试在单词列表中查找最常用的单词。到目前为止,这是我的代码:

uniWords = unique(lower(words));
for i = 1:length(words)
    for j = 1:length(uniWords)
        if (uniWords(j) == lower(words(i)))
            freq(j) = freq(j) + 1;
        end
    end
end

当我尝试运行脚本时,我收到以下错误:

Undefined function 'eq' for input arguments of
type 'cell'.

Error in Biweekly3 (line 106)
    if (uniWords(j) == lower(words(i)))

感谢任何帮助!

【问题讨论】:

    标签: string matlab compare cell-array


    【解决方案1】:

    你需要用{}提取单元格的内容

    strcmpi(uniWords{j},words{i})
    

    另外,我建议将字符串与strcmp 或在本例中为strcmpi, which ignores case 进行比较,这样您就不需要调用lower

    在字符串上使用== 时要小心,因为它们的长度必须相同,否则会出错:

    >> s1='first';
    >> s2='second';
    >> s1==s2
    Error using  == 
    Matrix dimensions must agree. 
    

    【讨论】:

    • +1 明智的建议。但是你忘记了一个重要的:矢量化! :-P
    • 是的,是的,是的... ;)
    【解决方案2】:

    不需要循环。 unique 为您提供每个单词的唯一标识符,然后您可以将每个标识符的出现次数与sparse 相加。从中您可以轻松找到最大值和最大化的单词:

    [~, ~, jj ] = unique(lower(words));
    freq = full(sparse(ones(1,length(jj)),jj,1)); % number of occurrences of each word
    m = max(freq);
    result = lower(words(jj(freq==m))); % return more than one word if there's a tie
    

    例如,用

    words = {'The','hello','one','bye','the','one'}
    

    结果是

    >> result
    
    result = 
    
        'one'    'the'
    

    【讨论】:

      【解决方案3】:

      我猜你需要这样做:

      if (uniWords{j} == lower(words{i}))
      

      另外,我建议not using i and j as variables in MATLAB

      更新

      正如 Chappjc 指出的那样,最好使用strcmp(或者在您的情况下使用strcmpi 并跳过lower),因为您想忽略大小写。

      【讨论】:

      • 问题中的代码还有另一个问题。对于不同长度的字符串,使用== 将给出Matrix dimensions must agree.
      猜你喜欢
      • 2011-03-14
      • 2019-07-03
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多