How to count occurrences of a letter?
1 回表示 (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (2 件)
Henrik
2014 年 12 月 5 日
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.
0 件のコメント
Star Strider
2014 年 12 月 5 日
The histc function is your friend for the second part. Note that it takes alphanumeric inputs for both the data and the bin ranges.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!