Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

fortran - sum only on certain dimension

I have a Fortran 90array (matrix) like:

REAL(8),DIMENSION(Xmax, Ymax, Zmax, Xmax, Ymax, Zmax) :: Mat

I read through my matrix in this way:

    DO X1=1,Xmax
      Do Y1=1,Ymax
        DO Z1=1,Zmax 

           DO Xv=1,Xmax
              Do Yv=1,Ymax
                DO Zv=1,Zmax 

                   Mat(X1, Y1, Z1, Xv, Yv, Zv)


           END DO
         END DO
        END DO
      END DO
    END DO
  END DO

I would like to create a new matrix NewMat (dimension(Xmax, Ymax, Zmax) only) which will contain for each (Xv, Yv, Zv) the sum of all respectively (X1, Y1, Z1) from my initial matrix.

My question is: Do I need to iterate to sum? Or is there a way to use some function? what would be more efficient?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're almost certainly looking for the intrinsic sum function which can be used to reduce an array (by addition) from rank n to rank n-1. So the expression

 sum(mat, dim=6)

will 'flatten' the 6th dimension of mat. I'm not entirely sure that I understand exactly what you are trying to do, but the assignment

 newmat = sum(sum(sum(mat, dim=6), dim=5), dim=4)

might satisfy your needs. I haven't got Fortran on this machine, and if I had I'd probably balk at setting up a rank-6 array to test it. So, if it isn't quite what you want fiddle around until you get it..

This probably isn't any faster than nesting loops, and it's arguably harder to read, but it does look like it was written by someone who understands modern Fortran's array operations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...