Charnum Char_counter help please

1 view (last 30 days)
nicola Braham
nicola Braham on 3 Sep 2020
Commented: Walter Roberson on 4 Sep 2020
Hi - for those familiar with this assignment.. any help appreciated -
second test is failing saying returning 1.. im not sure if it should return -1 or 0 for this and not sure if i have attempted to fix it correctly either way.. here is what i have..
function charnum = char_counter (fname, character)
total = 0;
fid = fopen(fname, 'r');
if fid < 0 || ~ischar(character) || numel(character) > 1;
charnum = -1;
return
end
oneline = fgets(fid);
for ii = oneline(1:end);
if ii == character;
total = total + 1
end
charnum = total;
end
fclose(fid);
end
  1 Comment
Walter Roberson
Walter Roberson on 3 Sep 2020
Note: you also have one of the very common bugs. If the file open works, but the parameter is not a scalar character, then your code leaves the file open when it returns.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 3 Sep 2020
Your code is only reading one line from the file, instead of reading all lines from the file.
  2 Comments
nicola Braham
nicola Braham on 4 Sep 2020
Does this fix it? I can't seem to submit it to check..
function charnum = char_counter (fname, character)
total = 0;
if ~ischar(character) || numel(character) > 1;
charnum = -1;
return;
end
fid = fopen(fname,'r');
if fid < 0;
charnum = -1;
return
end
oneline = fgets(fid);
for ii = oneline(1:end);
if ii == character;
total = total + 1;
oneline = fgets(fid)
end
charnum = total;
end
Walter Roberson
Walter Roberson on 4 Sep 2020
No, fgets() returns a character vector, and when you
for ii = oneline(1:end)
that is the same as
for ii = oneline
which in turn executes by setting ii to each element of the vector oneline in turn. (That is valid code in itself.)
So you are looping testing one character at a time from the line you read in. And you have suggested modifying the code so that each time you locate a copy of the character of interest, you replace the content of oneline with the content of the next line of the file. But remember the same character can occur more than once per line, so you would not want to be doing that. And it wouldn't work anyhow: when you start a for loop, MATLAB takes a copy of all of the variables involved in the for statement so any modifications to those variables will not affect the for loop.
You should be instead switching to have two layers of loop. The outer loop should be concerned with reading full lines until there is nothing left in the file. The inner loop should be concerned with proceeding character by character through the line that was read.
(Or, you know, you could vectorize counting the characters so you only had the outer loop...)

Sign in to comment.

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!