How to count occurrences of a letter?
Mostrar comentarios más antiguos
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
oldgrade=input('Enter letter grades (without spaces in between) ','s');
x=sscanf(oldgrade, '%c'); for i=1 : length(x)
switch x(i)
case {'a','A'}
grade = 'F';
case {'b','B'}
grade = 'D';
case {'c','C'}
grade = 'C';
case {'d','D'}
grade = 'B';
case {'f','F'}
grade = 'A';
case {'y','Y'}
grade = 'W';
end
fprintf('%s %s,', grade)
end
Respuestas (2)
Henrik
el 5 de Dic. de 2014
A quick and dirty solution could be
F_count=0;
switch x(i)
case {'a','A'}
grade = 'F';
F_count=F_count+1;
etc.
There are probably much more efficient solutions, though.
Star Strider
el 5 de Dic. de 2014
1 voto
The histc function is your friend for the second part. Note that it takes alphanumeric inputs for both the data and the bin ranges.
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!