# How to count occurrences of a letter?

6 views (last 30 days)
Jarred on 5 Dec 2014
Answered: Star Strider on 5 Dec 2014
The question is as follows: a. Your job is to write a function called CrazyGrade that will take in the string and flip the grades according to the following specifications: A becomes F B becomes D C remains unchanged D becomes B F becomes A Y becomes W Your function should take in a string as an input argument and return the inverted string as an output argument. You may assume that the input string will only consist of valid letter grades.
b. * To make matters worse, he wants you to tell him his grade distribution. So write a second function GradeDist to return the number of A's, B's, etc. So if there are 4 A's, 16 B's, 18 C's, 10 D's, 4 F's, and 3 W's, your function should return [4 16 18 10 4 3].*
I am working on part b but cannot figure out how to count the occurences with what I have so far. my code so far looks as follows:
clc,clear
x=sscanf(oldgrade, '%c'); for i=1 : length(x)
switch x(i)
case {'a','A'}
case {'b','B'}
case {'c','C'}
case {'d','D'}
case {'f','F'}
case {'y','Y'}
end
end

Henrik on 5 Dec 2014
A quick and dirty solution could be
F_count=0;
switch x(i)
case {'a','A'}
F_count=F_count+1;
etc.
There are probably much more efficient solutions, though.

Star Strider on 5 Dec 2014
The histc function is your friend for the second part. Note that it takes alphanumeric inputs for both the data and the bin ranges.