sum only on certain dimension

2019-07-29 22:04发布

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?

标签: sum fortran
1条回答
成全新的幸福
2楼-- · 2019-07-29 22:09

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.

查看更多
登录 后发表回答