필터 지우기
필터 지우기

Charnum Char_counter help please

조회 수: 2 (최근 30일)
nicola Braham
nicola Braham 2020년 9월 3일
댓글: Walter Roberson 2020년 9월 4일
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
Walter Roberson
Walter Roberson 2020년 9월 3일
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.

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

답변 (1개)

Walter Roberson
Walter Roberson 2020년 9월 3일
Your code is only reading one line from the file, instead of reading all lines from the file.
  댓글 수: 2
nicola Braham
nicola Braham 2020년 9월 4일
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 2020년 9월 4일
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...)

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by