Question: Code in MATLAB MatlabFunction Problem 1 Write a function with the header: function [wordCount] = myWordCounter(fid, keyword ) which takes a file pointer to a
Code in MATLAB
MatlabFunction Problem 1
Write a function with the header: function [wordCount] = myWordCounter(fid, keyword ) which takes a file pointer to a text file and a keyword and reads each line of the text file, counting every instance of the keyword. The function returns wordCount which is the total number of occurances of keyword in the text file. Note that in order to pass a file pointer, you must create one as shown in the test cases below, and be sure to close it (as shown) afterwards so that the file may be reopened. Note that the function should be case sensitive and but should also find instances of words with "the" in it (e.g., "there"). Sample text files CalNewport.txt and FinancialData.txt are provided. HINT: lookup (via Matlab help and Google) built-in function "feof" and fgetl. NOTE: Your fid value will be different than what is shown here. Matlab will simply choose the next available integer not used by another file handle. A value of -1 however, means Matlab was unable to open the file, probably because the place you stored it is not in the Matlab path.
HELPFUL HINTS!
When Matlab successfully opens a file with fopen, it will return a positive integer. This integer is known as a "file handle" and can be used to refer to that opened file until you close the file with fclose. In Problem 1, I use the variable "fid" to hold the file handle. Use fgetl to read one line of text from your text file at a time and assign it to a variable like this: lineStr = fgetl(fid); Every time you type fgetl, Matlab will move down one line in the file. The "thing" that is moving down is called a "file pointer" and it keeps track of where (which character) in a file Matlab is currently reading. Use strfind to look for the keyword like this: wordPositions = strfind(lineStr, keyword); Then you can count how many elements are in wordPositions to figure out how many times keyword showed up in lineStr; Use a while loop that looks like this: while ~feof(fid)
end This will look at what the file pointer is pointing to and if it is a special "end of file" ASCII character, feof(fid) will return "true".
FIXED MISTAKE: Your code should find all instances of keyword (of the same case) even if keyword is embedded in another word (e.g., "the" in "there" WILL BE COUNTED).
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
