MATLAB: What is wrong with the script

https://in.mathworks.com/matlabcentral/answers/275847-how-to-count-the-number-of-each-character-from-a-text-file-and-the-frequency-of-it

This code is for Char_Count problem. It is showing error when I run this program.
Error :
" Test with all visible characters
Variable charnum has an incorrect value.
When testing with '#' your solution returned -1 which isincorrect.(0)
For more details I'm attaching required files !
For Problem : Check screenshot (151).png
For Error : Check screen shot(150).png
Files for testing : simple.txt and Frankenstein-by-Shelley.txt
I think now you can help me out !
SCRIPT :
function charnum=char_counter(fname,character)
fid=fopen(fname,'rt');
if fid<0
charnum=-1;
return
end
if fid>0 && ischar(character)
C=double(character);
oneline=fgets(fid);
flag=0;
N=-1;
while ischar(oneline)
X=double(oneline);
Z=length(X);
for i=1:Z
if C==X(i)
flag=flag+1;
end
end
oneline=fgets(fid);
end
if flag==0
charnum=N;
else
charnum=flag;
end
else
charnum=-1;
end
fclose(fid);

Best Answer

N=-1;
if flag==0
charnum=N;
In the case that no matches for the character are found, you are returning N where N is -1. However, you are instructed to only return -1 if the file cannot be opened or the character parameter is not a valid character. If you do not find any copies of a character, then the number of characters found would be 0.