%Chapter 7,  Fig 7.6
%Eric Dubois, updated 2018-12-13
%To normalize Eizo RGB phosphor spectral densities  and plot color matching
%functions 
% data files obtained from CVRL website
%Data files should be placed in a data directory on the MATLAB path.
clear all, close all;
%Compute the xyz chromaticity coordinates of the Eizo phosphors.
lami = 400:2:700; %wavelengths to use for plot
%Read and interpolate EIZO RGB spectral densities
load EIZO_Norm.txt;
lamrgb = EIZO_Norm(:,1);
RGB = interp1(lamrgb,EIZO_Norm(:,2:4),lami,'spline');
%read and interpolate xyz color matching functions
xyz = dlmread('data/ciexyz31.txt',',');
lamxyz = xyz(:,1);
xyzi = interp1(lamxyz,xyz(:,2:4),lami,'spline');
%unnormalized tristimulus values
C = xyzi'*RGB;
%chromaticities
xyzrgb = C * inv(diag(sum(C)));
%reference white (D65)
xyzd = [.3127 .3290 .3582]';
XYZd = xyzd./xyzd(2);
%solve for RGB luminances
F = [xyzrgb(:,1)./xyzrgb(2,1) xyzrgb(:,2)./xyzrgb(2,2) xyzrgb(:,3)./xyzrgb(2,3)];
RGBL = F \ XYZd;
% compute the A matrix
A = [F(:,1)*RGBL(1) F(:,2)*RGBL(2) F(:,3)*RGBL(3)];
AI = inv(A);
%normalized spectral densities to give correct luminance
norm = RGBL./C(2,:)';
RGBnorm = RGB*diag(RGBL./C(2,:)');
%normalized tristimulus values
Cn = xyzi'*RGBnorm;
%compute the RGB color matching functions
RGBcmf = xyzi*AI';
%plot the color matching functions
figure;
plot(lami,RGBcmf(:,1),'r',lami,RGBcmf(:,2),'g',lami,RGBcmf(:,3),'b');
xlabel('Wavelength (nm)');
ylabel('Tristimulus values');
axis([400 700 -1 3]);
text(465,2,'b'), text(545,1.7,'g'), text(600,2.5,'r');
set(gcf,'Color',[1 1 1]);
set(gca,'fontname','times')          %set the plot font to Times