Write a function called digit_counter that takes the name of a text file as input and returns the number of digits (i.e., any of the characters, 0-to-9) that the file contains. If there is a problem opening the file, the function returns -1. WARNING:

1 view (last 30 days)
Hi, I was wondering why this does not work? Do i need to do nested for loops with i and j to traverse through the file ?
function [num] = digit_counter(filename)
fid = fopen(filename, 'r');
if fid < 0
error('error opening file%s\n', filename)
end
n = fread(fid,1, 'double');
dims = fread(fid,n, 'double');
A = fread(fid, 'double');
A = reshape(A, dims);
counter = 0 ;
for i = 1 : size(A)
if A(i) == 0 || A(i) == 1 ||A(i) == 2 || A(i) == 3 || A(i) == 4 || A(i) == 5 || A(i) == 6 || A(i) == 7 || A(i) == 8 || A(i) == 9
counter = counter + 1 ;
end
end
num = counter ;
fclose(fid) ;
end
  4 Comments
Emma Sellers
Emma Sellers on 8 Jan 2019
function [num] = digit_counter(filename)
fid = fopen(filename, 'r');
if fid < 0
num = -1 ;
else
A = fprintf(fid,'%4.4f\n',filename);
[m, n] = size(A);
counter = 0 ;
for j = 1 : n
for i = 1 : m
if A(i,j) == 0 || A(i,j) == 1 ||A(i,j) == 2 || A(i,j) == 3 || A(i,j) == 4 || A(i,j) == 5 || A(i,j) == 6 || A(i,j) == 7 || A(i,j) == 8 || A(i,j) == 9
counter = counter + 1 ;
end
end
end
num = counter ;
fclose(fid) ;
end

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 8 Jan 2019
This should get you started:
function num = digit_counter(fnm)
fid = fopen(fnm,'rt');
if fid<3
num = -1;
else
vec = fread(fid,[1,Inf],'char');
fclose(fid);
num = nnz(isstrprop(char(vec),'digit'));
end
end
  5 Comments
Rik
Rik on 8 Jan 2019
@Stephen, it does. I didn't test the code, so I needed to re-read the doc to confirm that it ignores white-space (and probably stops when it sees it).
I currently tend to use my own readfile function, which uses fileread on Matlab and fgetl on Octave. That odd choice of functions has more to do with the difficulty of detecting the encoding, as well as keeping a wide range of compatible releases, but it has so far worked on my test cases.

Sign in to comment.

Categories

Find more on Language Support 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!