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 次查看(过去 30 天)
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 个评论
Emma Sellers
Emma Sellers 2019-1-8
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

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2019-1-8
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 个评论
Rik
Rik 2019-1-8
@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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by