how o count he number of occurences of a string in an external text file?

6 views (last 30 days)
I would like to count he number of occurences that the string 'ALG' has, considering an external text file and one occurence per line.
For instance, if my text file has 7 lines with the string 'ALG' (among other things), the variable c should be 7.
Right now , the code that I have is this:
n=130 %(number of lines of txt file)
fid=fopen('C:\fer\a.txt','r')
for I = 1:n
s=char(fid(I));
k = strncmp(s,'ALG',3);
However, at the line "s=char(fid(I));" I am getting the following error:
Index exceeds the number of array elements (1).
I am using MATLAB 2018b
Any help is appreciated,
Thank you,
Hugo

Accepted Answer

Star Strider
Star Strider on 25 Sep 2020
The function you want is probably fgetl (or related functions) rather than char.
Then try:
s = fgetl(fid);
There are likely a few other ways to solve this.
In any event, fopen generates one file identifier, so subscripting it will throw that error.
If you are not already doing it, summing ‘k’ in each iteration will count the occurrences.
When you have read the file, remember to include:
fclose(fid);
to close the file.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!