    PROGRAM nag_lin_lsq_ex02

      ! 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_qr_fac, nag_qr_orth, nag_lin_lsq_sol_qr
      USE nag_write_mat, ONLY : nag_write_gen_mat, nag_write_tri_mat
      ! .. Implicit None Statement ..
      IMPLICIT NONE
      ! .. Intrinsic Functions ..
      INTRINSIC KIND, MIN
      ! .. Parameters ..
      INTEGER, PARAMETER :: wp = KIND(1.0D0)
      ! .. Local Scalars ..
      INTEGER :: i, m, n, ns
      REAL (wp) :: rcond, std_err
      ! .. Local Arrays ..
      INTEGER, ALLOCATABLE :: pivot(:)
      REAL (wp), ALLOCATABLE :: a(:,:), b(:), bb(:), q(:,:), tau(:), x(:)
      ! .. Executable Statements ..
      WRITE (nag_std_out,*) 'Example Program Results for nag_lin_lsq_ex02'

      READ (nag_std_in,*)          ! Skip heading in data file
      READ (nag_std_in,*) m, n
      ns = MIN(m,n)

      ALLOCATE (pivot(n),a(m,n),b(m),bb(m),q(m,ns),tau(ns), &
       x(n))                            ! Allocate storage

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

      ! Compute the QR factorization

      pivot = 0

      CALL nag_qr_fac(a,tau,pivot=pivot,rcond=rcond)

      WRITE (nag_std_out,*)

      CALL nag_write_tri_mat('upper',a(:n,:),format='(1X,F7.4)', &
       title='Matrix R')

      WRITE (nag_std_out,'(1X,A,ES11.2)') 'Estimated condition number =', &
       1/rcond

      ! Compute the leading min(m,n) columns of Q

      CALL nag_qr_orth(a,tau,q=q)

      WRITE (nag_std_out,*)

      CALL nag_write_gen_mat(q,format='(1X,F7.4)',title='Leading columns of Q' &
       )

      ! Compute the solution, assuming that A has full rank

      CALL nag_lin_lsq_sol_qr(a,tau,b,x,pivot=pivot,std_err=std_err)

      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) 'Solution assuming that A has full rank'
      WRITE (nag_std_out,'(3X,F7.4)') x
      WRITE (nag_std_out,'(1X,A,F7.4)') 'standard error =', std_err

      ! Compute the solution, assuming that A has rank 4

      b = bb

      CALL nag_lin_lsq_sol_qr(a,tau,b,x,pivot=pivot,rank=4,std_err=std_err)

      WRITE (nag_std_out,*)
      WRITE (nag_std_out,*) 'Solution assuming that A has rank 4'
      WRITE (nag_std_out,'(3X,F7.4)') x
      WRITE (nag_std_out,'(1X,A,F7.4)') 'standard error =', std_err

      DEALLOCATE (pivot,a,b,bb,q,tau,x) ! Deallocate storage

    END PROGRAM nag_lin_lsq_ex02
