查找指定字符串中指定子字符串的位置(MATLAB)

Finding location of specified substring in a specified string (MATLAB)

我有一个简单的问题需要帮助。我相信我的代码几乎完成了,但我在处理特定代码行时遇到了问题。

我有一道作业题(2 个部分)要求我找出一个蛋白质(字符串)是否在特定位置(位置)具有指定的基序(子字符串)。这是第一部分,函数和代码如下所示:

function output = Motif_Match(motif,protein,location)
%This code wil print a '1' if the motif occurs in the protein starting
at the given location, else it wil print a '0'
for k = 1:location %Iterates through specified location
    if protein(1, [k, k+1]) == motif; % if the location matches the protein and motif
       output = 1;  
    else
       output = 0;
    end
 end

这部分我是答对了,例子如下:

p = 'MGNAAAAKKGN'

m = 'GN'

Motif_Match(m,p,2)

ans = 

   1

我坚持的问题的第二部分是采用基序和蛋白质以及 return 包含基序在蛋白质中出现的位置的向量。为此,我正在调用我以前的代码,我不应该使用任何使这变得容易的函数,例如 strfind、find、hist、strcmp 等。

到目前为止,我的代码是:

function output = Motif_Find(motif,protein)
[r,c] = size(protein)
output = zeros(r,c)
for k = 1:c-1
      if Motif_Match(motif,protein,k) == 1;
         output(k) = protein(k)
      else 
         output = [];
      end
end

我认为这段代码的第 6 行有问题。我对此的想法是,我希望输出为我提供位置,并且这一行中的代码不正确,但我似乎想不出其他任何东西。应该发生的情况的示例如下:

p = 'MGNAAAAKKGN';

m = 'GN';

Motif_Find(m,p)

ans = 

   2      10

所以我的问题是,如何让我的代码为我提供位置?我已经坚持了很长一段时间,似乎无法解决这个问题。任何帮助将不胜感激!

谢谢大家!

你们很亲近。

output(k) = protein(k)

应该是

output(k) = k

这是因为我们只需要匹配的位置 K。使用 protien(k) 将为我们提供蛋白质字符串中位置 K 处的字符。

另外,我最后要做的就是 return 非零元素。最简单的方法是只使用除了 vector/matrix

之外没有参数的 find 命令

所以在你的循环之后就这样做

output = find(output); %returns only non zero elements

编辑

我刚刚注意到另一个问题 output = []; 表示将输出设置为空数组。这不是您想要的,我想您的意思是 output(k) = 0; 这就是您没有得到预期结果的原因。但实际上,因为您已经将整个数组设为零,所以您根本不需要它。总之,代码应该是这样的。我还用 length 替换了你的 size 因为你的蛋白质是线性序列,而不是二维矩阵

function output = Motif_Find(motif,protein)
protein_len = length(protein)
motif_len = length(motif)
output = zeros(1,protein_len)

%notice here I changed this to motif_length. think of it this way, if the
%length is 4, we don't need to search the last 3,2,or 1 protein groups
for k = 1:protein_len-motif_len + 1
      if Motif_Match(motif,protein,k) == 1;
         output(k) = k;
      %we don't really need these lines, since the array already has zeros
      %else 
      %   output(k) = 0;
      end
end

%returns only nonzero elements
output = find(output);