How to count occurrences of a letter?

조회 수: 1 (최근 30일)
Jarred
Jarred 2014년 12월 5일
답변: Star Strider 2014년 12월 5일
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

답변 (2개)

Henrik
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.

Star Strider
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.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by