%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Distribution of ECTS-grades (E-A) among students with locale grades.
%
% The code can handle any number of students from 1 student and up and any
% local grade system
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Created by Per Warfvinge per.warfvinge@chemeng.lth.se
% Lund University, LTH (Faculty of Engineering)
%
% Web (Swedish): http://www.ceq.lth.se/ECTScalc/
% Web (English): http://www.ceq.lth.se/ECTScalc/?lang=en
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


Cdata=input('Give current number of students on each local grade cohort [S1 S2 ... Sn]: ');
Ldata=input('Give long term percentages for each local grade cohort [%n1 %n2 .. % nn]: ');
size(Cdata);n1=ans(2);size(Ldata);n2=ans(2);
if n1~=n2 disp('ERROR: Input data vectors do not have the same dimensions'), return, end
if sum(Ldata)~=100 disp('ERROR: Percentages do not add up to 100'), return, end

ECTSmatrix=ectsdistribution(Cdata,Ldata);
if abs(sum(sum(ECTSmatrix))- sum(Cdata))>0.1 disp('WARNING: Distribution of mismatch of'),diff,disp('students') , end
disp(' '),disp('Columns represent local grades (lower to higher)'),disp('Rows represent ECTS-grades from E-A'), ECTSmatrix




function ECTSmatrix=ectsdistribution(Cdata,Ldata)

% Cdata = number of 3, 4 and 5 in the current group
% Ldata = long term percentages of 3, 4 and 5 

N=sum(Cdata);
size(Cdata);n=ans(2);      % n= number of cohorts in current data

for i=1:n
    C(i)=sum(Cdata(1:i))/N;    % C(i) = current percentiles
    L(i)=sum(Ldata(1:i))/100.;  % L(i) = long term percentiles
end

P=[0.1 0.35 0.65 0.9 1];    % ECTS percentiles

% mapping of current data on long-term data
for i=1:4
    Q(i)=percentiles(P(i),C,L)+0.0000001; 
end
Q(5)=1.0;

ECTS(1)=floor((N+0.5)*Q(1));
for i=2:5
    ECTS(i)=floor((N+0.5)*Q(i))-sum(ECTS(1:(i-1)));
end

% spreading out of the students on the ECTS-grades
for j=1:n
for i=1:5
    ECTSmatrix(i,j)=min(ECTS(i),Cdata(j)); % Number in current group j that should have ECTS-grade i
    Cdata(j)=Cdata(j)-ECTSmatrix(i,j) ;       % Reduce the current group j with those that got  ECTS-grade i

end 

ECTS=ECTS-ECTSmatrix(:,j)';

end % ECTSmatrix is the output from the function









function Q=percentiles(P,C,L)

% Calculate the normal grade index corresponding to an ECTS-percentile
size(C);n=ans(2);

for i=1:n % find right segment index "seg" by checking if P>L(i)
    if P < L(i) seg = i; break, end;
end;

if      seg<2 j=P/L(1);
else    j=(P-(seg*L(seg-1)-(seg-1)*L(seg)))/(L(seg)-L(seg-1));
end;

% Calculuate the corresponding percentile within the current student group
js=floor(j);
if      js<1 Q=j*C(1);
else    Q=j*(C(js+1)-C(js))+(1+js)*C(js)-(js)*C(1+js);
end;