    PROGRAM nag_lin_lsq_ex06

      ! Example Program Text for nag_lin_lsq
      ! NAG fl90, Release 4. NAG Copyright 2000.

      ! .. Use Statements ..
      USE nag_examples_io, ONLY : nag_std_in, nag_std_out
      USE nag_lin_lsq, ONLY : nag_lin_lsq_sol, nag_lin_lsq_sol_svd
      USE nag_write_mat, ONLY : nag_write_gen_mat
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Intrinsic Functions ..
      INTRINSIC KIND, MIN
      ! .. Parameters ..
      INTEGER, PARAMETER :: wp = KIND(1.0D0)
      ! .. Local Scalars ..
      INTEGER :: i, m, n, nrhs, ns, rank
      REAL (wp) :: tol
      ! .. Local Arrays ..
      REAL (wp), ALLOCATABLE :: sigma(:), std_err_b(:), std_err_ls(:)
      COMPLEX (wp), ALLOCATABLE :: a(:,:), b(:,:), x_b(:,:), x_ls(:,:)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_lin_lsq_ex06'

      READ (nag_std_in,*)          ! Skip heading in data file
      READ (nag_std_in,*) m, n, nrhs

      ns = MIN(m,n)
      tol = 0.005_wp

      ALLOCATE (a(m,n),b(m,nrhs),sigma(ns),std_err_b(nrhs),std_err_ls(nrhs), &
       x_b(n,nrhs),x_ls(n,nrhs))   ! Allocate storage

      READ (nag_std_in,*) (a(i,:),i=1,m)
      READ (nag_std_in,*) (b(i,:),i=1,m)

      ! Compute the minimum norm solution

      CALL nag_lin_lsq_sol(a,b,x_ls,sigma=sigma,tol=tol,rank=rank, &
       std_err=std_err_ls)

      WRITE (nag_std_out,*)

      CALL nag_write_gen_mat(x_ls,int_col_labels=.TRUE.,format='(F7.4)', &
       title='Minimum norm solutions (one solution per column)')

      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) ' Standard errors'
      WRITE (nag_std_out,'(11X,4(F8.4:,10X))') std_err_ls
      WRITE (nag_std_out,*)
      WRITE (nag_std_out,'(2X,''tol '',6X,F7.4)') tol
      WRITE (nag_std_out,'(2X,''rank'',6X,I7)') rank

      ! Compute the basic solution

      CALL nag_lin_lsq_sol_svd(a(:ns,:),sigma,b,x_b,solution='Basic',tol=tol, &
       rank=rank,std_err=std_err_b)

      WRITE (nag_std_out,*)

      CALL nag_write_gen_mat(x_b,int_col_labels=.TRUE.,format='(F7.4)', &
       title='Basic solutions (one solution per column)')

      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) ' Standard errors'
      WRITE (nag_std_out,'(11X,4(F8.4:,10X))') std_err_b
      WRITE (nag_std_out,*)
      WRITE (nag_std_out,'(2X,''tol '',6X,F7.4)') tol
      WRITE (nag_std_out,'(2X,''rank'',6X,I7)') rank

      DEALLOCATE (a,b,sigma,std_err_b,std_err_ls,x_b, &
       x_ls)                       ! Deallocate storage

    END PROGRAM nag_lin_lsq_ex06
