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

1 visualizzazione (ultimi 30 giorni)
function[c]=digit_counter(filename)
fid=fopen(filename,'rt');
if fid<0
error('error opening file %s', filename);
end
A = char(fread(fid,inf)).';
c=length(A);
fclose(fid);
end

Risposte (2)

Walter Roberson
Walter Roberson il 23 Set 2016
Your code returns the number of bytes in the file. The requirements are that it return the number of digits in the file -- that is, the total number of occurrences of any of the characters '0', '1', '2', '3', '4', '5', '6', '7', '8', or '9'

Srishti Saha
Srishti Saha il 13 Mag 2018
A simple function as this would work:
function n = digit_counter(fname)
n = -1;
fid = fopen(fname,'r');
if fid >= 0
n = sum(isstrprop(fread(fid,inf,'char=>char'),'digit'));
fclose(fid);
end
end

Categorie

Scopri di più su Function Creation in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by