function s = cdf_to_sample ( c_x, c_y, c_n, s_n )

%*****************************************************************************80
%
%% cdf_to_sample() samples a discretized CDF.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    10 August 2016
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real C_X(C_N), the points at which the CDF is defined.
%
%    real C_Y(C_N), the values of the CDF.
%
%    integer C_N, the number of points at which the CDF is defined.
%
%    integer S_N, the number of samples desired.
%
%  Output:
%
%    real S(S_N), the sample points.
%
  s = zeros ( s_n, 1 );

  r1 = rand ( s_n, 1 );
  r2 = rand ( s_n, 2 );
%
%  Each R1 is a CDF value.  Bracket it between C_X(LEFT) and C_X(LEFT+1).
%
  left = r8vec_bracket4 ( c_n, c_y, s_n, r1 );
%
%  Each R2 is a relative weight for the left endpoint of the interval.
%  As sure as I almost know MATLAB, this will never work!
%
% s(1:s_n) =         r2(1:s_n)   .* c_x(left(1:s_n)) ...
%          + ( 1.0 - r2(1:s_n) ) .* c_x(left(1:s_n)+1);

  for i = 1 : s_n
    s(i) =             r2(i)   * c_x(left(i)) ...
             + ( 1.0 - r2(i) ) * c_x(left(i)+1);
  end

  return
end
