Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Please help replace the integers in this function.

조회 수: 1 (최근 30일)
Kevin Smith
Kevin Smith 2017년 10월 23일
편집: Stephen23 2017년 10월 23일
I have a function replaceMultiples that I am trying to write. it is supposed to take an input as a filename (fname) of a text file, and a natural number (num). Where each line of the text file contains one or more integers, separated by a blank space. Go through the text file fname line by line and replaces each integer that is a multiple of num by the integer divided by num. And write the modified text file to a text file with the same name as the original file, but started with ’updated# ’, where # represents the number num.
Here is my script so far:
function n=replaceMultiples2(fname, num)
ifh=fopen(fname,'r'); %open the file for reading
ofn=['updated_', num, fname]; %creates the output file name
ofh=fopen(ofn, 'wt'); %open the output file for writing
ln=' '; %initiation of ln
while ischar(ln)
ln=fgetl(ifh);
if ischar(ln)
ln=fgetl(ifh); %grab the next line from the file
while ~isempty(ln)
[tk,ln]=strtok(ln); %get the first token
n=length(tk);
i=1:1:n;
if mod(str2num(tk(i))/num)==0; %calls integers divisable by num
fprintf(ofh,' %s',tk); %write it to the input file
else
fprintf(ofh, '%s ', tk);
end
end
fprintf(ofh,'\n');
end
end
fclose(ifh);
fclose(ofh);
There are some errors. An example input would look like this:
replaceMultiples(example.txt,3)
Where the example text is this txt file:
123 571 33
14 15 18
6 9
28 25 33 36
Then after inputting this into the function the new file should be called "updated3_example.txt" and should look like this:
41 571 11
14 5 6
2 3
28 25 11 12
If someone could please help me fix my script so that it is functional I would really appreciate it. I dont think it is too far off from being functional. I believe my biggest problem right now is finding the correct way to test if the integer is divisible by n.

답변 (0개)

이 질문은 마감되었습니다.

제품

Community Treasure Hunt

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

Start Hunting!

Translated by