仅在某个维度上求和 [英] sum only on certain dimension

查看:16
本文介绍了仅在某个维度上求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Fortran 90array(矩阵),例如:

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

我想创建一个新矩阵 NewMat(仅限维度(Xmax, Ymax, Zmax)),它将包含每个 (Xv, Yv, Zv)来自我的初始矩阵的所有 (X1, Y1, Z1) 的总和.

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 函数,该函数可用于将数组(通过加法)从排名中减少 nn-1 进行排名.所以表达式

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)

将展平"mat 的第 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)

可能会满足您的需求.我在这台机器上没有 Fortran,如果有的话,我可能会犹豫设置一个 rank-6 数组来测试它.所以,如果它不是你想要的,直到你得到它..

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..

这可能并不比嵌套循环快,而且它可能更难阅读,但它看起来确实是由了解现代 Fortran 数组操作的人编写的.

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.

这篇关于仅在某个维度上求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆