How do we get an average associated with an input of string arrays?

3 views (last 30 days)
So we have a function made already as letter_grade_num
function letter_grade = letter_grade_num(grade)
switch grade
case 'A'
letter_grade = 7
case 'B'
letter_grade = 6
case 'C'
letter_grade = 5
case 'D'
letter_grade = 4
case 'E'
letter_grade = 3
case 'F'
letter_grade = 2
case 'G'
letter_grade = 1
end
end
This above function will take one letter grade and will return a number associated to it like:
letter_grade_num('A')
= 7
But now we want a function that uses this as a sub-function and takes an array of strings as an input and gives an average in numbers as an output. How would we do that?

Answers (1)

Walter Roberson
Walter Roberson on 4 Oct 2015
mean( cellfun(@letter_grade_num, ArrayOfStrings) )
  5 Comments
Walter Roberson
Walter Roberson on 4 Oct 2015
function g_avg = Our_Main_Function( Array_Of_Strings)
g_avg = mean( cellfun( @letter_grade_num, Array_Of_Strings) );
end
Now it uses Our_Main_Function. A test case is
MyArrayOfStrings = {'A', 'C', 'D', 'A', 'B', 'B'};
OurMainFunction( MyArrayOfStrings )
Note: an array of strings is different than an array of characters! An array of characters would be (for example) 'ACDABB' . It would be completely valid for the assignment to have required an array of characters instead of an array of strings.
Imagine, though, that the letter to number conversion had to take into account '+' and '-', like grades of 'A+' and 'B-'. If you were to put those in as arrays of strings, no change would be required to cellfun version: you could just have
MyArrayOfStrings = {'A-', 'C+', 'D+', 'A', 'B', 'B+'};
and nothing about OurMainFunction would have to change. But if you were using an array of characters instead, 'A-C+D+ABB+' then OurMainFunction would have to be changed to figure out where the boundaries were, to break this apart into individual grades, taking into account that a grade is not necessarily followed by a + or -. This would make the task of OurMainFunction harder.
When you are coding, you usually want to make the task of your routines easier -- it makes it easier to write the routines correctly and makes it easier to write code that executes quickly. Saving memory by using 'A-C+D+ABB+' is something you prefer to only have to do at I/O interfaces (reading from file or user, writing to file) or if you need to work with pretty big arrays.

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!