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

时间:2015-03-27 17:48:16

标签: string matlab loops substring

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

我有一个任务问题(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

我坚持的问题的第二部分是采用主题和蛋白质并返回含有蛋白质中基序出现位置的载体。要做到这一点,我正在使用我以前的代码调用,我不应该使用任何使这简单的函数,如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

所以我的问题是,如何让我的代码给我这些位置?我已经坚持了很长一段时间,似乎无法随心所欲。任何帮助将不胜感激!

谢谢大家!

1 个答案:

答案 0 :(得分:0)

你非常接近。

output(k) = protein(k)

应该是

output(k) = k

这是因为我们只想要比赛的位置K.使用protien(k)将为我们提供蛋白质字符串中K位置的字符。

我要做的最后一件事就是只返回非零元素。最简单的方法是使用除了vector / matrix

之外没有参数的find命令

所以在循环之后就这样做

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

修改

我刚注意到另一个问题output = [];表示将输出设置为空数组。这不是你想要的我认为你的意思是output(k) = 0;这就是为什么你没有得到你期望的结果。但是真的,因为你已经使整个数组为零,所以根本不需要它。总之,代码看起来应该是这样的。我还将size替换为length,因为您的蛋白质是线性序列,而不是2d matricies

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);