【问题标题】:MatLab - Cellfun where func = strcmp Find where str changes in a cell arrayMatLab - Cellfun where func = strcmp 查找单元格数组中 str 的变化位置
【发布时间】:2015-06-06 21:04:05
【问题描述】:

我有一个字符串元胞数组,我想检测字符串更改的次数并获取更改的索引。鉴于 Matlab 的 cellfun 函数,我试图使用它而不是循环。这是所有的代码。感谢您的时间、反馈和 cmets。

% Cell Array Example
names(1:10)={'OFF'};
names(11:15)={'J1 - 1'};
names(16:22)={'J1 - 2'};
names(23:27)={'J2 - 1'};
names(28)={'Off'};
names=names';

% My cellfun code
cellfun(@(x,y) strcmp(x,y), names(1:2:end),names(2:2:end));

我的预期结果是一个长度为 27 (length(names)-1) 的向量,其中向量中有 4 个零表示 strcmp 函数发现 4 个比较不相等的情况。

实际结果是一个长度为 14 的向量,并且只有 2 个零。非常感谢您解释为什么会出现这种意外结果。

谢谢

【问题讨论】:

    标签: matlab cell-array strcmp


    【解决方案1】:

    Matt 提供的answer 正确显示了您的代码存在的问题。但是,您可以直接使用strcmp,因为它接受两个字符串元胞数组作为输入

    >> strcmp(names(1:end-1), names(2:end))
    ans =
      Columns 1 through 14
         1     1     1     1     1     1     1     1     1     0     1     1     1     1
      Columns 15 through 27
         0     1     1     1     1     1     1     0     1     1     1     1     0
    

    【讨论】:

    • 是的,这是一个更好的解决方案
    【解决方案2】:

    您可以使用unique 将字符串转换为数字标签,然后应用diff 来检测更改:

    [~, ~, u] = unique(names);
    result = ~diff(u);
    

    【讨论】:

      【解决方案3】:

      如果我正确理解您的问题,您应该将names(1:end-1)names(2:end) 进行比较。即比较字符串 1 和字符串 2,比较字符串 2 和字符串 3,以此类推。您改为使用 2 的步幅,将字符串 1 与字符串 2 进行比较,将字符串 3 与字符串 4 进行比较,依此类推。您可以通过将最后一行更改为:

      cellfun(@(x,y) strcmp(x,y), names(1:end-1),names(2:end))
      

      那么结果是:

       Columns 1 through 20:
      
       1   1   1   1   1   1   1   1   1   0   1   1   1   1   0   1   1   1   1   1
      
       Columns 21 through 27:
      
       1   0   1   1   1   1   0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        • 1970-01-01
        • 2013-08-06
        • 1970-01-01
        • 2014-03-22
        • 2017-09-12
        • 2017-04-01
        相关资源
        最近更新 更多