Jeff Faraci
Jeff Faraci

Reputation: 413

optimizing part of code with array constructor

The following simple example code gives correct results. However, I'd like to optimize it or make it more efficient. The constructor array, y, that I create in order to generate the position line spacing works, but it is very clumsy looking and inconvenient since the numbers in it are very specific. I want to make the numbers in the y array more general variables that depend on the earlier defined parameters in my code. Here is the code and then I'll be more clear:

PROGRAM TestRuns
IMPLICIT NONE
INTEGER :: i, j, k !matrix indices (i,j), spatial index k
INTEGER,PARAMETER :: n=5 !matrix size
REAL, PARAMETER :: a = -6, b =6 !end points of grid
REAL :: h !step size on position grid
REAL :: y(0:6) = (/(k, k=-6,6,2)/) ! generating spatial grid array
DOUBLE PRECISION :: M(n,n) !nxn matrix

h = (b-a)/(n+1)

DO i = 1,n
    DO j = 1,n
        IF (i .EQ. j) THEN
            M(i,j) = y(i)**2
        ELSE
            M(i,j) = 0
        END IF
    END DO
END DO

END PROGRAM TestRuns

Instead of having

 REAL :: y(0:6) = (/(k, k=-6,6,2)/)   ! this line of code works but is not helpful in generalizing my code at all.

I really want to write something more general such as :

 REAL :: y(0:n+1) = (/(k, k=a,b,h)/)

I always specify, a,b,n first in my code, so from these parameters I want to be able to then calculate h and the array y. I don't want to have to automatically put the values of array y in by hand as I'm doing now.

Upvotes: 0

Views: 61

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

You'll have discovered that your compiler doesn't like the line

REAL :: y(0:n+1) = (/(k, k=a,b,h)/)

Change it to

REAL :: y(0:n+1) = [(k, k=INT(a),INT(b),2)] 

that is, make the lower and upper bounds for k into integers. I doubt that you will ever be able to measure any increase in efficiency, but this change might appeal to your notions of nice-looking and convenient code.

You might also want to tweak the way you initialise M. I'd have written your two loops as

M = 0.0
DO i = 1,n
   M(i,i) = y(i)**2
END DO

Overall, though, your question is a bit vague so I'm not sure how satisfactory this answer will be. If not enough, clarify your question some more.

Upvotes: 1

Related Questions