【问题标题】:Most efficient way of splitting long string into substrings in MATLAB在 MATLAB 中将长字符串拆分为子字符串的最有效方法
【发布时间】:2016-03-01 02:10:24
【问题描述】:

我正在研究 MATLAB 中的一个函数,它比较两个基因序列并确定它们的相似性。为此,我将两个序列划分为更小的子字符串,方法是使用 for 循环遍历它们,一次移动一个核苷酸并将子字符串添加到单元阵列中。

例如,子字符串长度为 4 的字符串 ATGCAAAT 不会被拆分为

ATGC , AAAT

而是作为

ATCG、TGCA、GCAA、CAAA、AAAT

我试图加快函数的执行速度,因为这两个 for 循环提供了几乎 90% 的执行时间,我想知道 MATLAB 中是否有更快的方法来执行此操作。

这是我目前使用的代码:

 SubstrSequence1 = {};                                                
 SubstrSequence2 = {};
 for i = 1:length(Sequence1)-(SubstringLength-1)                
     SubstrSequence1 = [SubstrSequence1, Sequence1(i:i+SubstringLength-1)];
 end

 for i = 1:length(Sequence2)-(SubstringLength-1)                
     SubstrSequence2 = [SubstrSequence2, Sequence2(i:i+SubstringLength-1)]; 
 end

【问题讨论】:

    标签: string matlab split substring


    【解决方案1】:

    一种方法是生成一个索引矩阵,以适当地提取您想要的子字符串:

    >> sequence = 'ATGCAAAT';
    >> subSequenceLength = 4;
    >> numSubSequence = length(sequence) - subSequenceLength + 1;
    >> idx = repmat((1:numSubSequence)', 1, subSequenceLength) + repmat(0:subSequenceLength-1, numSubSequence, 1);
    >> result = sequence(idx)
    
        result =
    
            ATGC
            TGCA
            GCAA
            CAAA
            AAAT
    

    【讨论】:

      【解决方案2】:

      这是使用hankel 获取SubstrSequence1 的一种方法-

      A = 1:numel(Sequence1);
      out = cellstr(Sequence1(hankel(A(1:SubstringLength),A(SubstringLength:end)).'))
      

      您可以按照相同的步骤找到SubstrSequence2

      示例运行 -

      >> Sequence1 = 'ATGCAAAT';
      >> SubstringLength = 4;
      >> A = 1:numel(Sequence1);
      >> cellstr(Sequence1(hankel(A(1:SubstringLength),A(SubstringLength:end)).'))
      ans = 
          'ATGC'
          'TGCA'
          'GCAA'
          'CAAA'
          'AAAT'
      

      【讨论】:

      • 我开始使用 hankel,但无法让它工作!
      • @LuisMendo 我从 bsxfun 开始,但为时已晚! :)
      • 我确信你已经开始了:-P
      【解决方案3】:

      这个怎么样?

      str = 'ATGCAAAT';
      n = 4;
      strs = str(bsxfun(@plus, 1:n, (0:numel(str)-n).'));
      

      结果是一个二维字符数组

      strs =
      ATGC
      TGCA
      GCAA
      CAAA
      AAAT
      

      所以部分字符串是strs(1,:)strs(2,:) 等。

      如果您希望结果为 字符串的单元格数组,请在末尾添加:

      strs = cellstr(strs);
      

      生产

      strs = 
          'ATGC'
          'TGCA'
          'GCAA'
          'CAAA'
          'AAAT'
      

      然后部分字符串为strs{1}strs{2}等。

      【讨论】:

      • 非常感谢,这很好用。它比我使用的 for 循环快 3 倍左右,并且比这里的其他建议快一点。
      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 2011-04-15
      • 2015-05-29
      • 2011-04-11
      • 1970-01-01
      • 2011-02-22
      相关资源
      最近更新 更多