필터 지우기
필터 지우기

Embedding a while into a for loop

조회 수: 1 (최근 30일)
Maroulator
Maroulator 2016년 8월 5일
댓글: Maroulator 2016년 8월 6일
I am trying to write a function which counts the amount of times a character pattern (p) can be found within another string; I am trying to use loops only. Below is the code that I have; I get no error, then again my code doesn't seem to execute. I think I am missing smth obvious and would appreciate a second pair of eyes; I have set dna='ATCCCGG' and p='CG'. Any input is welcome; many thanks in advance.
function [count] = countPattern_CM(dna,p)
%countPattern_CM This function finds out how many times a pattern p occurs
%in data
if length(p)>length(dna)
msgbox(['The pattern(p) that you entered is longer than the dna',...
'\nstring. Please enter new pattern(p)! ']);
else
count=0; %This variable captures the occurence of
%the pattern p within dna
for i=1:length(dna)
k=i+length(p)-1;
while k<=length(dna);
if strcmp(dna(1,i:k),p)==1;
count=count+1;
else
continue;
end
end
end
end
end
  댓글 수: 1
Maroulator
Maroulator 2016년 8월 6일
Stephen,
Thanks for the answer; you are correct, this is an academic exercise;)

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2016년 8월 5일
편집: Stephen23 2016년 8월 5일
You are turning something simple into something complicated. Just one loop is required:
dna = 'ATCCCGGCG';
p = 'CG';
%
Np = numel(p)-1;
count = 0;
for k = 1:numel(dna)-Np
count = count + strcmp(dna(k+(0:Np)),p);
end
However this task its a total waste of both your time and the computer's time: using inbuilt functions will be simpler, faster, and much more robust. Unless you have been given this as some academic exercise, there is no reason to try to reinvent the wheel by writing your own slower, buggier code. For example, this will always be faster and more reliable than anything you can write:
numel(strfind(dna,p))

추가 답변 (0개)

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by