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

MatLab Write a function with the header: function [wordcount] = myWordCounter (f

ID: 3603783 • Letter: M

Question

MatLab

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 occurrences of keyword in the text file. Note that 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 NOT be case sensitive but should also find instances of words which contain keyword (e.g., it should count "there" when keyword is "the"). Sample text files GettingAhead.txt and Passion.txt are provided HINT: lookup (via Matlab help and Google) built-in function "feof" and "fget 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 nof in the Matlab path Test Cases: >> fid = fopen ( ' GettingAhead . txt ' , >> n = myWordcounter (fid, 'skill') ' r ' ) ; n a >>fclose (fid); >> fid fopen ( ' GettingAhead . txt ' , >> n = myWordcounter (fid, 'Sk11L') ' r ' ) ; n F

Explanation / Answer

ANSWER::

fid = fopen(filename);

words = textscan(fid, '%s');
for i=1:numel(words{1,1})
ind = find(isstrprop(words{1,1}{i,1}, 'alphanum') == 0);
words{1,1}{i,1}(ind)=[];
end

for i = 1:numel(words{1,1})
if size(words{1,1}{i,1}, 2) == 0
words{1,1}{i,1} = ' ';
end
end

unique_words = unique(words{1,1});

freq = zeros(numel(unique_words), 1);

for i = 1:numel(unique_words)
if max(unique_words{i} ~= ' ')
for j = 1:numel(words{1,1})
if strcmp(words{1,1}(j), unique_words{i})
freq(i) = freq(i) + 1;
end
end
end
end

u_freq = unique(freq);

sorted_freq = sort(u_freq, 'descend');

results={ 'WORD' 'FREQ' 'REL. FREQ' };

for i = 1:min(numel(find(sorted_freq > 1)), num)
ind = find(freq == sorted_freq(i));
results{i+1, 1} = unique_words{ind};
results{i+1, 2} = unique(freq(ind));
results{i+1, 3} = sprintf('%.4f%s', unique(freq(ind)/numel(words{1,1}))*100, '%');
end

sprintf('*NOTE: Only words that appeared more than once are displayed below Total number of words in "%s" = %d Total
number of unique words = %d', filename, numel(words{1,1}), numel(find(freq)))

status = fclose(fid);