필터 지우기
필터 지우기

Function to count the number of characters in a text file

조회 수: 3 (최근 30일)
Sara Ismail-Sutton
Sara Ismail-Sutton 2020년 9월 16일
댓글: Sara Ismail-Sutton 2020년 9월 16일
Hi
I've wrote the following code so far, but I'm having the problem that sum(charnums) returns the latest given value of charnums and doesn't sum over them. (as I can tell the code would, but I'm quite new to matlab and can't think how to write it with some index, for example i've tried charnums(oneline)=b2(oneline)... etc , as the 'oneline' is what is being iterated over I thought... but than it says dimensions exceed ... error .
many thanks
function[charnum]=liness(fname,character)
fid=fopen(fname,'rt')
if ( fid<0)
charnum=-1
return
else
a=findstr(oneline,character);
[b1,b2]=size(a);
charnums=b2
while ischar(oneline)
fprintf('%s',oneline)
a=findstr(oneline,character);
[b1,b2]=size(a);
charnums=b2
oneline=fgets(fid)
end
end
charnum=sum(b2)
fclose(fid)
end

답변 (1개)

Walter Roberson
Walter Roberson 2020년 9월 16일
a=findstr(oneline,character);
Your assignment requires you to determine that character is really a valid character and return -1 if it is not.
You have not defined oneline at that point.
[b1,b2]=size(a);
charnums=b2
hint: numel()
fprintf('%s',oneline)
You are not asked to display the content of oneline -- but it would not hurt to do so for debugging purposes, as long as you remove that afterwards.
charnums=b2
You are overwriting charnums each iteration of the while loop.
You also never use the value of charnums
charnum=sum(b2)
You overwrote all of b2 each iteration of the while loop.
Hint:
total = total + current_value
Also, your current logic has a problem in the case where the file exists and is readable but is completely empty, as the first read from such a file would immediately return an indication of end-of-file, and you should not be asking about the size of that end-of-file marker.
  댓글 수: 4
Walter Roberson
Walter Roberson 2020년 9월 16일
counter = 0;
while whatever
do something
counter = counter + 1;
[b1, b2(counter)] = size(a);
end
and then afterwards you can sum the vector b2.
However, this is really unnecessary and inefficient. Consider
counter = 0;
while whatever
do something
[b1, b2] = size(a);
counter = counter + b2;
end
Sara Ismail-Sutton
Sara Ismail-Sutton 2020년 9월 16일
okay many thanks!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by