% xyz2rgb.m
%
% Converts xyz tristimulus values to rgb value for display.  
%
% by Chuck DiMarzio, Northeastern University, December 2008
%
% Taken from http://psy.ucsd.edu/~rdbeer/convertRGB.m
%
%  Usage:   
%  (1)   rgb=xyz2rgb(xyz);
%  where xyz is a column vector [x,y,z]' returns rgb as a column
%  vector [r,g,b]'
%
%
%  (2)   rgb=xyz2rgb(xyz);
%  where xyz is a 3-D array, with the third dimension being x,y,z
%  returns rgb as a 3-D array, with the third dimension being r,g,b
%  with the right color coordinates to match the xyz tristiumulus values.
%  To display the resulting image, use either
%
%  image(max(0,rgb/max(max(max(rgb))))); or
%  image((max(rgb,0)./repmat(max(rgb,[],3),[1,1,3])));
%
%  The first will produce the closest to a true image with darker and
%  lighter shades.  The second will show the colors but remove any
%  brightness effects, so that every rgb triple will have a maximum value
%  of 1 in it.
%
%  (3)  matrix_xyz2rgb=xyz2rgb(0) or
%       matrix_xyz2rgb=xyz2rgb('matrix')
%
function rgb=xyz2rgb(xyz);
mxyz2rgb =[
    1.7168   -0.4554   -0.2614;...
   -0.9984    2.0272   -0.0287;...
    0.2816   -0.5718    1.2901];
if(xyz==0|ischar(xyz)); % For xyz a scalar zero or string, return the matrix.
  rgb=mxyz2rgb;
  return;
end;

test=length(size(xyz));
if(test==3);  % this is a color image with x in xyz(:,:1), etc:  compuete
              % xyz2rgb on the third dimension 
[xsize,ysize,three]=size(xyz);       
xyza=reshape(xyz,xsize*ysize,3)';
rgba=mxyz2rgb*(xyza);
rgb=reshape(rgba',xsize,ysize,3);
return;
end;
if(test<3 & size(xyz,1)==3);  % Otherwise, treat this as a matrix
                              % multiplication where the  input can be a
                              % column vector or multiple column vectors.
                              % Make sure that there are three rows in
                              % xyz. 
  rgb=mxyz2rgb*(xyz);
return;
end;
rgb=0;  % If xyz doesn't fit and of the above formats return zero.
