How to search for a letter within a string
Show older comments
I have a code where combinations such as ABC DEF GHI and JKL occur in a matrix of 4 * 60.
ABC GHI JKL ..... GHI ABC GHI ..... DEF JKL DEF ..... JKL DEF ABC .....
How do I individually find out how many time each letter has occurred in this random permutation of letter combinations. Furthermore, I also want to know the occurrence of letter pairs, such as how many times C occurred with the next triplet starting with D, G or J.
Answers (1)
Image Analyst
on 29 Mar 2016
Edited: Image Analyst
on 29 Mar 2016
To count how many times a letter occurs, use sum and ==
aLocations = (charArray == 'A');
numberOfAs = sum(aLocations(:));
charArray == 'A' is basically a binary map of where the A shows up in the matrix. If it's there, it shows up as a 1 in the result, and then sum() just counts up the number of ones.
To count how many times each letter is next to any other letter, use graycomatrix() in the Image Processing Toolbox. This function is meant for gray level images and computes the GLCM: "Gray Level Cooccurrence Matrix". However if you make an array where each element is the ASCII value of the letter, it will work fine. You get an array of 26 rows and 26 columns and to find out how many times one letter occurs next to another, just look up the right element in the matrix. For example to find out how many times B occurs next to D, look in row 2 (for B) and column 4 (for D) and you'll find the count. You can supply parameters to tell it where to look, like at all 8 neighbors or just one below or one to the right or whatever. Supply an actual array if you still need help.
Actually, on second thought, since you want occurrences in a triplet instead of immediately adjacent, you should use blockproc() - again, in the Image Processing Toolbox. Just slightly confusing but basically you can define a function that operates as a moving window of 3 elements long scans across your array in "jumps" of 3. So it would consider elements 1-3, then consider elements 4-6, then 7-9, etc. That function would be one you write to load up your cooccurrence matrix. I've attached an example of how to use blockproc - look at the myFilter function which is what you would change to create your cooccurrence matrix.
Categories
Find more on Convert Image Type in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!