
% File: Lab3parts3and4.m
%
% This is my solution to Parts 3 and 4 of Lab 3.
%
% Created by: Dr. C. S. Tritt
% Last revised: 2/13/07 (Version 1.0)
%
% Set-up (create and populate structure array).

student = struct ('Name',[],'Major',[],'Exam', [], 'Final',[]);

student(1).Name = 'Mary';
student(2).Name = 'Bill';
student(3).Name = 'Bob';
student(4).Name = 'Jill';
student(5).Name = 'Chuck';
student(1).Major = 'BE';
student(2).Major = 'BE';
student(3).Major = 'BE';
student(4).Major = 'BE';
student(5).Major = 'ME';
student(1).Exam(1) = 88;
student(2).Exam(1) = 66;
student(3).Exam(1) = 55;
student(4).Exam(1) = 20;
student(5).Exam(1) = 20;
student(1).Exam(2) = 89;
student(2).Exam(2) = 87;
student(3).Exam(2) = 88;
student(4).Exam(2) = 44;
student(5).Exam(2) = 44;
student(1).Exam(3) = 77;
student(2).Exam(3) = 99;
student(3).Exam(3) = 85;
student(4).Exam(3) = 55;
student(5).Exam(3) = 55;
student(1).Final = 88;
student(2).Final = 66;
student(3).Final = 80;
student(4).Final = 62;
student(5).Final = 66;

% Part 3 - Calculate and display averages. This can't be vectorized 
% because the sum function doesn't work with structure arrays.

% Initialize sums.

for n = 1:length(student(1).Exam)
   exam(n) = 0;
end

final = 0;

% Accumulate sums.

for n = 1:length(student(1).Exam)
   for m = 1:length(student)
      exam(n) = exam(n) + student(m).Exam(n);
   end   
end

for m = 1:length(student)
   final = final + student(m).Final;
end

% Calculate averages.

for n = 1:length(student(1).Exam)
   ave_exam(n) = exam(n)/length(student);
end

final_ave = final/length(student); 

% Display averages.

averages = ''; % Start with an empty string.

for n = 1:length(student(1).Exam)
   averages = [averages sprintf('Exam %2.0f: %3.2f \n', ...
      n, ave_exam(n))];
end

averages = [averages sprintf('Final Exam: %3.2f \n', final_ave)];

title = sprintf('Exam Averages');
msgbox(averages, title, 'modal'); % Modal doesn't work!

% Part 4 - Display of selected student data.

% It is a bit tricky to make the menu display accomidate varying 
% numbers and names of students. My approach is to build the menu
% function call using sprintf and then call it using the eval
% function.

% Build the menu function call string.

mstr = 'k = menu(''Student Selection''';  % Doubled quotes required.
for m = 1:length(student)
   mstr = [mstr sprintf(', ''%s''', student(m).Name)];
end
mstr = [mstr ');'];

% Use eval to call the menu function using the built string.

eval(mstr);

% Build the message box output string.

if k ~= 0 % Skip this if user cancels menu.
   info = sprintf('Name: %s\n', student(k).Name);
   info = [info sprintf('Major: %s\n', student(k).Major)];
   for n = 1:length(student(k).Exam)
      info = [info sprintf('Exam %2.0f: %4.1f\n', n, ...
         student(k).Exam(n))];
   end
   info = [info sprintf('Final: %4.1f', student(k).Final)];

   % Display it.

   msgbox(info, 'Student Information');
end