calculate the frequency of letters in words in matlab

Here is some sample code to calculate the frequency of letters in words using MATLAB:

main.m
% Define a string
inputStr = 'Hello World';

% Convert string to all lowercase
inputStr = lower(inputStr);

% Remove whitespace and non-alphabetic characters
inputStr = regexprep(inputStr, '[^a-z]', '');

% Create an array of unique characters in the string
uniqueChars = unique(inputStr);

% Loop through the unique characters and count the frequency of each
freq = zeros(length(uniqueChars), 1);

for ii = 1:length(uniqueChars)
    for jj = 1:length(inputStr)
        if inputStr(jj) == uniqueChars(ii)
            freq(ii) = freq(ii) + 1;
        end
    end
end

% Display the frequency of each character
for ii = 1:length(uniqueChars)
    fprintf('%c: %d\n', uniqueChars(ii), freq(ii));
end
696 chars
28 lines

This code first defines a string inputStr. We then convert this string to all lowercase so that we don't count 'H' and 'h' as different letters. We then remove all whitespace and non-alphabetic characters using regexprep.

Next, we create an array uniqueChars of all the unique characters in the string. We then loop through these unique characters and count the frequency of each. Finally, we display the frequency of each character using a loop and fprintf statement.

Note that this code assumes that the input string only contains alphabetic characters. If the input string can also contain numeric or special characters, you will need to modify the regular expression passed to regexprep accordingly.

gistlibby LogSnag