Hello,
I am doing an online course on matlab in coursera and I have come a cross a problem that seems hard for me to solve.
I need to write a function that takes the name of the text file and a paticular charater as input and then the function must count how many times the character is present in the file and return that number.
function charnum = char_counter(b,a)
fid = fopen(b,'r');
if fid < 0 || ~ischar(a) || length(a) == 0
charnum = -1;
return
end
t=0;
d=1;
while (d>0)
d = fgetl(fid);
x = strfind(d,a);
t = t + length(x);
end
charnum = t;
fclose(fid);
end
I have passed 3 out of 4 checks, following is the error that I am getting
Variable charnum has an incorrect value. When testing with ' ' your solution returned 1 which is incorrect. (75444).
I tried countin the number of " ' ' " as well and it seemed correct to,
I would like to the mistake that I am making.
Thanks
Hussain

6 commentaires

Ameer Hamza
Ameer Hamza le 28 Mar 2020
Can you give the function call when the function fails. What are the values of a and b.
Hussain Bhavnagarwala
Hussain Bhavnagarwala le 28 Mar 2020
The moderator of the forum said that It does not count spaces " ", but I tried that and it does, so I am not sure.
I am unable to see the inputs to the function. I can only see the errors
I am not sure about the issue. Maybe you can try this loop-free version.
char_counter('text.txt', ' ')
function charnum = char_counter(b,a)
fid = fopen(b,'r');
if fid < 0 || ~ischar(a) || isempty(a)
charnum = -1;
return
end
data = char(fread(fid)');
charnum = numel(strfind(data, a));
fclose(fid);
end
Adam Danz
Adam Danz le 28 Mar 2020
Modifié(e) : Adam Danz le 28 Mar 2020
I don't want to give the answer away because this is an assignment but this can be done with 1 line of code.
Hints:
  1. fileread() returns a char array
  2. sum(chararray == 'c')
  3. For case insensitivity, upper() or lower()
Image Analyst
Image Analyst le 29 Mar 2020
Adam, I'd put that down in the answer section so you can get credit for it. I was about to say the same thing.
Adam Danz
Adam Danz le 29 Mar 2020
Thanks, Image Analyst.

Connectez-vous pour commenter.

 Réponse acceptée

Adam Danz
Adam Danz le 29 Mar 2020
Modifié(e) : Adam Danz le 30 Mar 2020

0 votes

Here's a demo to count the instances of a character in a text file.
This demo searches for a space character ' ' and then replaces the space characters with squares so you can visually confirm the results.
This is the simple text file I'm reading in (also attached).
Read in the file and count the empty spaces ' '
idx shows the location of spaces.
c = fileread('myTextFile.txt');
idx = c == ' ';
sum(idx)
% ans =
% 67
To search for a case insensitive character, use upper() or lower().
idx = lower(c) == 'a';
Replace the spaces with squares
cCopy = c;
cCopy(idx) = char(746); % square character
disp(cCopy)
Spaces have been replaced with squares. Number of squares = 67

11 commentaires

Hussain Bhavnagarwala
Hussain Bhavnagarwala le 30 Mar 2020
Modifié(e) : Hussain Bhavnagarwala le 30 Mar 2020
Hi adam ,
Thanks for taking the time to write a solution
function charnum = char_counter1(b,a)
fid = fopen(b,'r');
if fid < 0 || ~ischar(a) || isempty(a)
charnum = -1;
return
end
f = lower(fileread(b));
charnum = sum(f=='a');
fclose(fid);
end
I am still getting a similar error :
Variable charnum has an incorrect value.
When testing with ' ' your solution returned 25788 which is incorrect. (75444)
I tried this function from @ameer hamza
data = char(fread(fid)');
charnum = numel(strfind(data, a));
fclose(fid);
This one seems to work, but I don not understand why ?( I would like to know as it will help me in the future)
Thanks
Hussain
Ameer Hamza
Ameer Hamza le 30 Mar 2020
Modifié(e) : Ameer Hamza le 30 Mar 2020
Hussain, I think you should try after removing the lower function from this code
f = fileread(b);
charnum = sum(f==a);
I am getting the following error
Variable charnum has an incorrect value.
When testing with ' ' your solution returned 25433 which is incorrect. (75444)
Can you paste your code here. There was another issue in your pasted code. Change
charnum = sum(f=='a');
to
charnum = sum(f==a);
Hussain Bhavnagarwala
Hussain Bhavnagarwala le 30 Mar 2020
Yes that was it !....
I feel so stupid now ....
Adam Danz
Adam Danz le 30 Mar 2020
Modifié(e) : Adam Danz le 30 Mar 2020
Your previous results returned the number of "a" characters.
I've updated my answer now that you've solved it using the method I was hinting at.
You'll notice that you don't need any of the fid parts of your code. In fact, your function can be reduced to one line.
Hussain Bhavnagarwala
Hussain Bhavnagarwala le 30 Mar 2020
I think the fid part was needed to check if the file had any content, the prompt had told us that we need to return -1 if the file is empty
Adam Danz
Adam Danz le 30 Mar 2020
Modifié(e) : Adam Danz le 30 Mar 2020
You could do the same thing using
function charnum = char_counter1(b,a)
f = fileread(b);
if isempty(f)
charnum = -1;
else
charnum = sum(lower(f) == lower(a));
end
That's the entire function.
Hussain Bhavnagarwala
Hussain Bhavnagarwala le 30 Mar 2020
I have miles to go in matlab I guess !!
Ameer Hamza
Ameer Hamza le 30 Mar 2020
The condition lower(f) == lower(a) should be carefully used. It is only valid for case-insensitive counting of characters.
Adam Danz
Adam Danz le 30 Mar 2020
Modifié(e) : Adam Danz le 30 Mar 2020
OP's code shared here shows
f = lower(fileread(b));
charnum = sum(f=='a');
which indicates a case insensitive search. There's no use in doing that unless the search key is also case insensitive. But it's good to explicitly point that out for the OP.
With an empty space search, case doesn't matter since upper(' ')==lower(' ').

Connectez-vous pour commenter.

Plus de réponses (3)

Rishi Diwan
Rishi Diwan le 23 Mai 2020

0 votes

function charnum = char_counter(fname,character)
fid = fopen(fname,'rt');
if fid <= 0 || ~ischar(character) || ~ischar(fname) || length(fname)==0 || length(character)==0 || isempty(fname) || isempty(character)
charnum=-1;
return;
end
c=0;
ol=fgets(fid);
while ischar(ol)
c=c+count(ol,character);
ol=fgets(fid);
end
charnum=c;
fclose(fid);
end

3 commentaires

Walter Roberson
Walter Roberson le 23 Mai 2020
if the file open succeeded but the other parameter is not a valid character then you are leaving the file open.
a shorter version of your code:
function charnum = char_counter(fname,character)
charnum = count(fileread(fname),character);
end
Walter Roberson
Walter Roberson le 4 Sep 2022
This turns out to be a homework assignment. The checks for file existing and for the input being a valid character are required as part of the assignment.

Connectez-vous pour commenter.

Ahsiur Rahman Nirjhar
Ahsiur Rahman Nirjhar le 24 Mai 2020

0 votes

function x=char_counter(a,b)
fid=fopen(a,'rt');
if fid <0 || ~ischar(b)
s=-1;
else
s=0;
oneline=fgets(fid);
while ischar(oneline)
s=s+sum(double(oneline)==double(b));
oneline=fgets(fid);
end
fclose(fid);
end
x=s;
Mert Yalcinoz
Mert Yalcinoz le 1 Fév 2022

0 votes

By looking other's people answers i have combined my code and got the result.
function charnum=char_counter(fname,character) %creating function
fid=fopen(fname,'rt');
if fid<0 || ~ischar(character) || length(character)==0 %conditions
charnum=-1;
return
end
a=0; %setting a total value for found desired string
b=fgets(fid); %for reading the first line, returns single line in a string
while ischar(b) %loop for each line
a=a+count(b,character); %summing when a character is found
b=fgets(fid); %if there is no new line, b becomes -1 and loop ends.
end
charnum=a; %setting output variable
fclose(fid);
end

1 commentaire

Walter Roberson
Walter Roberson le 1 Fév 2022
Suppose that a valid file name is passed in, but suppose that character is not a valid character or is empty. Then you set charnum=-1 and return... without having closed the file.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Customize Object Display for Classes dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by