% function to read in a file and count letter frequencies
function v=letter_freq(filename)
% read in file
fileID=fopen(filename);
input_text=fread(fileID)';
fclose(fileID);
counter=0;
% array to track letters=1-26 and blank=27
letter_count=zeros(27,1);
% keep only blanks and letters, cover to uppercase
% save counts of each
for k=1:length(input_text)
letter=input_text(k);
if letter ==32
counter=counter+1;
letter_count(27)=letter_count(27)+1;
plain_text(counter)=letter;
elseif (65<=letter)&&(letter<=90)
counter=counter+1;
letter_count(letter-64)=letter_count(letter-64)+1;
plain_text(counter)=letter;
elseif (97<=letter)&&(letter<=122)
counter= counter+1;
letter_count(letter-96)=letter_count(letter-96)+1;
plain_text(counter)=letter-32;
end
end
[s,v]=sort(letter_count,'descend');
%return
% bar plot of letter frequencies
figure;
hold on;
grid on;
letters={'A','B','C','D','E','F','G','H','I','J','K','L',...
'M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z','_'};
title({'Letter frequencies in file ',filename});
c1=categorical(letters);
h=bar(c1,letter_count);
% bar plot of sorted frequencies
figure;
hold on;
grid on;
title({'Sorted letter frequencies in file ',filename});
c2=categorical(letters(v));
bar(s);
set(gca, 'XTickLabel',letters(v), 'XTick',1:length(letters))

return