How can I create a for loop to count the number of letters in my array?
Mostrar comentarios más antiguos
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?
Respuesta aceptada
Más respuestas (1)
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 comentarios
Fope Ayo
el 20 de Nov. de 2018
"thanks for this but i need to relate it to my for loop"
This is MATLAB, so why bother using a for loop?
":...then use this for loop to calculate the GC ratio for the sequence"
You are wasting your time using loops:
>> V = 'ttgcgcatgcgcaca';
>> nnz(V=='g') / nnz(V=='c')
ans = 0.80000
Fope Ayo
el 20 de Nov. de 2018
Fope Ayo
el 20 de Nov. de 2018
Fope Ayo
el 20 de Nov. de 2018
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
el 20 de Nov. de 2018
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!