필터 지우기
필터 지우기

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:

조회 수: 2 (최근 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일
I noticed in the doc that it is used to create example files to later read with another function.
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