How can I create a for loop to count the number of letters in my array?

6 ビュー (過去 30 日間)
Fope Ayo
Fope Ayo 2018 年 11 月 20 日
コメント済み: Fope Ayo 2018 年 11 月 20 日
I have the following array:
bases = [ t t g c g c a t g c g c a c a ]
I want to create a for loop that loops through the array and counts the number of g’s within it.
do i use the if function?

採用された回答

madhan ravi
madhan ravi 2018 年 11 月 20 日
編集済み: madhan ravi 2018 年 11 月 20 日
Stephen's way is efficient but if you insist loop then:
bases = 't t g c g c a t g c g c a c a'
ctr=0;
for i = 1:numel(bases)
if bases(i)=='g'
ctr=ctr+1;
end
end
number_of_gs=ctr
  16 件のコメント
Fope Ayo
Fope Ayo 2018 年 11 月 20 日
@madhan ravi sorry i meant bases
Basically I am trying to use the for loop created which counts the number of two elements e.g g’s and c’s, then use this for loop to calculate the GC ratio for the sequence
Stephen23
Stephen23 2018 年 11 月 20 日
"Basically I am trying to use the for loop created which counts the number of two elements e.g g’s and c’s, then use this for loop to calculate the GC ratio for the sequence"
So is your aim to play around with loops, or is your aim to get answers from your code?

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

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 11 月 20 日
編集済み: Stephen23 2018 年 11 月 20 日
The simple MATLAB solution:
>> V = 'ttgcgcatgcgcaca';
>> nnz(V=='g')
ans = 4
Or to count occurances of all of the different letters:
>> U = unique(V)
U = 'acgt'
>> histc(V,U)
ans =
3 5 4 3
I.e. 'a' occurs three times, 'c' occurs five times, 'g' occurs four times, and 't' occurs three times.
To count how many times a specific substring occurs:
>> numel(strfind(V,'gc'))
ans = 4
I.e. the substring 'gc' occurs four times.
  7 件のコメント
Stephen23
Stephen23 2018 年 11 月 20 日
編集済み: Stephen23 2018 年 11 月 20 日
I often edit my comments for clarity and spelling. Some comments and answers that turn out to be superfluous to the discussion I will also remove.
I notice that you have opened a new question on this topic here:
which is clearer describing what you are actually trying to achieve. You should put a link back to this thread, so that readers of that new thread know what you have already tried and what information you have been given. Otherwise people often just give you the same solutions, which is unsatisfying for everyone involved.
Fope Ayo
Fope Ayo 2018 年 11 月 20 日
Once again, thanks for your insight and input.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by