next up previous contents
Next: Elements of object-oriented programming Up: Pointers and Targets Previous: Arrays of Pointers   Contents

Example: Sorting Vectors

Given N vectors of measurements (of different dimensions), write a program that sorts the set of vectors according to their mean; several vectors of equal mean are sorted according to their variance.

To represent each set of measurements, we choose the structure

type meas_set  
   real, dimension(:), pointer :: data  
   integer :: dim  
   real :: mean, dev  
end type meas_set
where the number of measured values in the set, dim, may vary; data holds the measured values, mean and dev the mean value and the standard deviation of the set of measurements.

Suppose we have a total of N_Meas data sets. For reasons that will become clear later, we want to work with pointers to objects of type Meas_Set; thus, we construct

type ptr_meas_set  
    type(meas_set), pointer :: v  
end type ptr_meas_set   
type(ptr_meas_set), dimension(n_meas) :: mx  
type(ptr_meas_set) :: tmp
Each measurement set will correspond to one entry in the vector mx.

We can read in the N_Meas measurement sets as follows. If there are still measured data sets to be read in, we allocate an object of the type Ptr_Meas_Set, then read in the number of points dim, allocate the vector data of dimension dim, read the measured values and store them in data.

do i=1,n_meas  
  allocate( mx(i)%v )  
  if (ierr.ne.0) .... ! some action  
  read(10,10) mx(i)%v%dim ! no. of data points  
  allocate( mx(i)%v%data(mx(i)%v%dim), stat=ierr) ! allocate data vector 
  if (ierr.ne.0) .... ! some action  
  read(10,10) mx(i)%v%data ! read data  
end do

After creating the storage and reading in the data, we can compute the mean and the deviation for each data set

do i=1,n_meas  
! compute the mean  
  mx(i)%v%mean = 0.0  
  do j=1,mx(i)%v%dim  
     mx(i)%v%mean = mx(i)%v%mean + mx(i)%v%data(j)  
  end do  
  mx(i)%v%mean = mx(i)%v%mean/mx(i)%v%dim  
! compute the deviation  
  mx(i)%v%dev = 0.0  
  do j=1,mx(i)%v%dim  
     mx(i)%v%dev = mx(i)%v%dev + (mx(i)%v%data(j)-mx(i)%v%mean)**2   
  end do  
  mx(i)%v%dev = sqrt(mx(i)%v%dev/mx(i)%v%dim)  
end do
Now we need to sort the measured data in increasing mean order. Since the sorting algorithms move the data around, and we want to avoid repeated copying of large measurement vectors, we introduced the array of pointers mx. Interchanging to elements of mx means interchanging two pointer values; this is a cheap operation, when compared to interchanging two 10,000-elements vectors.

The simplest sorting algorithm might look like

do k=1,n_meas  
   do i=1,n_meas-1  
     if(  mx(i)%v%mean >  mx(i+1)%v%mean ) then  
         tmp = mx(i+1)  
         mx(i+1) = mx(i)  
          mx(i) = tmp   
     end if  
   end do  
end do

next up previous contents
Next: Elements of object-oriented programming Up: Pointers and Targets Previous: Arrays of Pointers   Contents
Adrian Sandu 2001-08-26