Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Write a function that will accept a file name and two words. The function

ID: 3691907 • Letter: M

Question

MATLAB

Write a function that will accept a file name and two words. The function will open the file and read it one line at a time. If the line contains the first word passed to the function, replace that word with the second word passed to the function. This is essentially a find and replace function. All occurrences of the first word should be replaced. Assume capitalized words are different from non-capitalized words. For example, if you are replacing the word ‘see’ don’t replace ‘See’. The function should open a new file with the same name but with ‘New_’ add to the beginning of the file name.

Use this EMF.txt file. The new file will be named New_EMF.txt. Write the replaced text to the new file.

Explanation / Answer

function [ newLines ] = Untitled( filename,word1,word2 )
% Write a function that will accept a file name and two words.
% The function will open the file and read it one line at a time.
% If the line contains the first word passed to the function,
% replace that word with the second word passed to the function.
% This is essentially a find and replace function.

% All occurrences of the first word should be replaced.
% Assume capitalized words are different from non-capitalized words.
% For example, if you are replacing the word ‘see’ don’t replace ‘See’.
% The function should open a new file with the same name but with
% ‘New_’ add to the beginning of the file name.
%
% file=strcat(filename, '.txt');
file=filename;
new= strcat('NEW_',filename);


fid = fopen(file, 'r') %for read
fid2 = fopen(new, 'w') %for write

Lines={ }; % array that store the lines
while ~feof(fid)
line = fgetl(fid); % read all the line
Lines{end+1,1}=line;
end

newLines=strrep(Lines, word1, word2);

fprintf(fid2,'%s ',newLines{:});

fclose(fid2);
fclose(fid);
end