Function to count the number of characters in a text file
9 views (last 30 days)
Show older comments
Hi
I've wrote the following code so far, but I'm having the problem that sum(charnums) returns the latest given value of charnums and doesn't sum over them. (as I can tell the code would, but I'm quite new to matlab and can't think how to write it with some index, for example i've tried charnums(oneline)=b2(oneline)... etc , as the 'oneline' is what is being iterated over I thought... but than it says dimensions exceed ... error .
many thanks
function[charnum]=liness(fname,character)
fid=fopen(fname,'rt')
if ( fid<0)
charnum=-1
return
else
a=findstr(oneline,character);
[b1,b2]=size(a);
charnums=b2
while ischar(oneline)
fprintf('%s',oneline)
a=findstr(oneline,character);
[b1,b2]=size(a);
charnums=b2
oneline=fgets(fid)
end
end
charnum=sum(b2)
fclose(fid)
end
0 Comments
Answers (1)
Walter Roberson
on 16 Sep 2020
a=findstr(oneline,character);
Your assignment requires you to determine that character is really a valid character and return -1 if it is not.
You have not defined oneline at that point.
[b1,b2]=size(a);
charnums=b2
hint: numel()
fprintf('%s',oneline)
You are not asked to display the content of oneline -- but it would not hurt to do so for debugging purposes, as long as you remove that afterwards.
charnums=b2
You are overwriting charnums each iteration of the while loop.
You also never use the value of charnums
charnum=sum(b2)
You overwrote all of b2 each iteration of the while loop.
Hint:
total = total + current_value
Also, your current logic has a problem in the case where the file exists and is readable but is completely empty, as the first read from such a file would immediately return an indication of end-of-file, and you should not be asking about the size of that end-of-file marker.
4 Comments
Walter Roberson
on 16 Sep 2020
counter = 0;
while whatever
do something
counter = counter + 1;
[b1, b2(counter)] = size(a);
end
and then afterwards you can sum the vector b2.
However, this is really unnecessary and inefficient. Consider
counter = 0;
while whatever
do something
[b1, b2] = size(a);
counter = counter + b2;
end
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!