Silverfrost Forums

Welcome to our forums

Histogram error: Array subscript(s) out-of-bounds

27 Nov 2009 9:43 #5456

I am writing a code to make histogram. I created three subroutines. One would read data from an external file, second will calculate histogram and the last one will write the results. The subroutine histogram giving me the error. This is the data file http://www.sendspace.com/file/ydezb9 and the code is as shown below. Any help would be highly appreciated. Thanks!

PROGRAM histo
	IMPLICIT NONE
	
	INTEGER :: n, bin 
	REAL :: mode_value  
    REAL, DIMENSION(4096) :: velocity, hist_scale, hist  
    
	n = 4096
      bin = 50
		
	CALL READDATA(velocity,n)
	CALL HISTOGRAM(velocity,n,bin,hist_scale,hist,mode_value)	
        CALL WRITEDATA(bin,hist_scale,hist, mode_value) 
    
    CLOSE(UNIT = 3)
    CLOSE(UNIT = 9)

	STOP
END PROGRAM

SUBROUTINE READDATA(y,n)
	IMPLICIT NONE
	INTEGER :: i, ierr
    REAL :: xdummy
	INTEGER, INTENT(IN) :: n 
	REAL, INTENT(OUT), DIMENSION(n) :: y
	ierr = 0 
	OPEN (UNIT=3, FILE='sinedata.txt', STATUS='OLD', ACTION='READ', IOSTAT=ierr) 
	DO i = 1, n
	READ (3,*,IOSTAT=ierr) xdummy, y(i)
	END DO
	RETURN
END SUBROUTINE


SUBROUTINE HISTOGRAM(velocity,n,bin,hist_scale,hist,expected_value)
IMPLICIT NONE
    INTEGER, INTENT(IN) :: n,bin
	REAL, DIMENSION(n), INTENT(IN) :: velocity
	REAL, DIMENSION(bin), INTENT(OUT) :: hist, hist_scale
	REAL, INTENT(OUT) :: expected_value
	REAL :: container, min=0., maxx=2.
	INTEGER :: line, i, con
	hist=0
	DO i=1,n
		container=((velocity(i)-min)*(REAL(bin)/maxx))
		IF (container >= bin) container = bin-1
		line = int(container)+1 
		hist(line) = hist(line)+1
	END DO
	hist = hist/(n/REAL(bin))
	DO i = 1,bin
		hist_scale(i) = min+((i-1)*maxx/REAL(bin))
	END DO
	container = 0.
	DO i = 1,bin,1
		IF (container < hist(i)) THEN
			container = hist(i)
			con = i
		END IF
	END DO
	expected_value = (hist_scale(con)+hist_scale(con+1))/2.
	RETURN
END SUBROUTINE histogram
 

SUBROUTINE WRITEDATA(bin,hist_scale,hist, mode_value)
	IMPLICIT NONE
	INTEGER :: ierr, i
    INTEGER, INTENT(IN) :: bin
	REAL, INTENT(IN) :: mode_value
    REAL, INTENT(IN), DIMENSION(bin) :: hist_scale,hist
	WRITE(*,*) 'Mode Value = ', mode_value
    OPEN (UNIT=9, FILE='03 hist.txt', STATUS='REPLACE', ACTION='WRITE', IOSTAT=ierr)
		DO i = 1, bin
			WRITE(9,*) hist_scale(i), hist(i)
		 END DO         
RETURN
END SUBROUTINE
28 Nov 2009 9:58 #5458

You have negative velocities, yet you calculate the variable 'line' as if the minimum velocity is zero That causes the subscript to go negative on line 49.

You need to check the logic of your program and make sure that the statements mean what you want them to.

29 Nov 2009 7:32 #5459

Hi Mecej, I just figured that out and wanted to post the answer. Then I found yours. Absolutely right you are. Thanks for your time.

Please login to reply.