How to Count occurrences?

Given a text: ‘tagtacagccagtagagttgattccaaggaagtccggctgttgtagagtagc’ and a three-character target pattern (for example: ‘TAG’ ), your program should identify all target patterns in the text and output the number of occurrences of the target pattern.
Sample output Text:tagtacagccagtagagttgattccaaggaagtccggctgttgtagagtagctag
Target:TAG
Number of TAG:5
Target:tag
Number of tag:5
Target:GTa
Number of cag:2
Target:exit Program terminated!

3 件のコメント

Guillaume
Guillaume 2019 年 10 月 8 日
So? It's trivial to do with strfind in just one short line of code.
What effort, if any, have you made?
Cre'Shawn Dabney
Cre'Shawn Dabney 2019 年 10 月 8 日
Hello, I am confused about the looping and case sensitivity part. In other words I can perform the first output which is
Text:tagtacagccagtagagttgattccaaggaagtccggctgttgtagagtagctag
Target:TAG
Number of TAG:5
But I cant seem to produce the rest of the outputs. This is what I used to produce the first output:
clear;clc;
text=input('Enter text:','s');
pattern=input('Target:','s');
count=0;
n=size(text,2);
m=size(pattern,2);
for i=1:n-m
%sunstring find
temp=text(i:i+m-1);
%comapre
if(strcmp(temp,pattern))
count=count+1;
end
end
fprintf('Pattern count: %d\n',count);
Priyadharshini A.R
Priyadharshini A.R 2021 年 5 月 10 日
Hello Dabney,
The loop must go on till n-m+1 so that it can traverse till last element in text

サインインしてコメントする。

回答 (2 件)

Jan
Jan 2021 年 5 月 10 日

1 投票

t = 'tagtacagccagtagagttgattccaaggaagtccggctgttgtagagtagc';
tag = 'tag';
result = sum(strfind(lower(t), lower(tag)))
Alaster Meehan
Alaster Meehan 2019 年 10 月 8 日

0 投票

strcmpi ignors case
Cheers Alaster

1 件のコメント

Cre'Shawn Dabney
Cre'Shawn Dabney 2019 年 10 月 8 日
Thank you for your answer. I am still confused on how to write this code. Could you possibly demonstrate how? If not thank you so much for your participation!

サインインしてコメントする。

質問済み:

2019 年 10 月 8 日

回答済み:

Jan
2021 年 5 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by