Open a text file and count the number of digits
18 views (last 30 days)
Show older comments
Hi, I need a function that takes as an input the name of another file (either .txt or .m), opens it and counts the number of digits present.
This is what I have so far but it always returns either -1(file could not be opened) or 0.
function num = digit_counter(filename)
fid=fopen(filename,'rt');
if fid<0
num=-1;
else
num=0;
for k=0:9
n=count(filename,'1');
num=num+n;
end
end
Thanks in advance!
3 Comments
dpb
on 17 Sep 2018
What's the content of the file?
Depending on what it is, there are some much more clever "Matlab'y" ways to do this.
Accepted Answer
dpb
on 17 Sep 2018
Edited: dpb
on 17 Sep 2018
function [num,n] = digit_counter(filename)
% Returns total number and optional distribution of integers 0 thru 9
% in text file filename
fid=fopen(filename,'r'); % NB: include error handling for real
f=fread(fid,'char'); % read as character array full file
n=histc(f,'0':'9'); % find, bin the integers in the file
num=sum(n); % get the total number
fid=fclose(fid);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Import and Export 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!