%function svd_project_test ( )

%*****************************************************************************80
%
%% SVD_PROJECT_TEST demonstrates projection using SVD vectors.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 December 2018
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SVD_PROJECT_TEST:\n' );
  fprintf ( 1, '  Compute singular vectors for x(i)^(j-1).\n' );
  fprintf ( 1, '  Then take an arbitrary vector.\n' );
  fprintf ( 1, '  Approximate it with 0, 1, 2, ... singular vectors.\n' );
%
%  Get the data array.
%
  xmin = -1.0;
  xmax = +1.0;
  m = 51;
  n = 8;

  x = linspace ( xmin, xmax, m );
  x = x';
  data = powers_data ( xmin, xmax, m, n );
%
%  Compute N SVD vectors.
%
  [ svd_vec, svd_val, avg ] = svd_vectors ( data, n );

  avg = avg / norm ( avg );
%
%  Get a data vector.
%
  se = sin ( x ) + 1 ./ ( x.^2 + 0.25 );
%
%  Break the data vector into:
%  SE0: constant + multiple of average
%  SE1: remainder.
%
  beta = ( se(m) - se(1) ) / ( avg(m) - avg(1) );
  alpha = se(1) - beta * avg(1);
  se0 = alpha + beta * avg;
  se1 = se - se0;
%
%  Construct approximations.
%
  fig_num = 0;

  for j = 0 : n

    fig_num = fig_num + 1;
    figure ( fig_num )
    clf

    if ( j == 0 ) 
      sa = se0;
    else
      c = svd_vec(:,j)' * se1;
      sa = sa + c * svd_vec(:,j);
    end

    hold on
    plot ( x, se, 'b-', 'linewidth', 3 );
    plot ( x, sa, 'r-', 'linewidth', 3 );   
    grid ( 'on' );
    label = sprintf ( 'SVD projection using %d vectors\n', j );
    title ( label );
    hold off
    filename = sprintf ( 'svd_project_test_%d.png', j );
    print ( '-dpng', filename );
    fprintf ( 1, '  Graphics saved as "%s"\n', filename );

  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SVD_PROJECT_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

%  return
%end
