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

6 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Star Strider
Star Strider il 25 Set 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.

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by