通过正确定义索引列表来提高代码效率 [英] Improving efficiency of code by correctly defining a list of indices

查看:109
本文介绍了通过正确定义索引列表来提高代码效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了这个问题避免通过重复复制代码-结构化if语句/do循环,以确定如何使我的代码更高效.该解决方案极大地帮助了我,如下所示.

I asked this question avoid duplicating code by re-structuring if statement/do loop in order to determine how I could make my code more efficient. The solution greatly helped me and is shown below.

function grad(psi)
  implicit none
  integer, parameter :: nx = 24, ny = 24, nxx = nx / 2, nyy = ny / 2
  real, parameter :: pi = 4 * atan(1.0), f0 = pi ** 2 * 1.3
  complex, dimension(3,3,-nx:nx,-ny:ny) :: psi, grad

  grad(:,:,-nx+1:nx-1,-ny+1:ny-1) = psi(:,:,-nx+2:nx,-ny+1:ny-1)
  grad(:,:,0,0) = psi(:,:,1,0)
  grad(:,:,[-nxx,nxx],[-nyy,nyy,ny]) = psi(:,:,[-nxx+1,nxx+1],[-nyy,nyy,ny]) - f0 * psi(:,:,[-nxx,nxx],[-nyy,nyy,ny])

end

但是我现在需要进一步优化代码.

However I need to optimize my code even more now.

在上面的示例中,有一个部分由

In the example above there is a portion given by

grad(:,:,[-nxx,nxx],[-nyy,nyy,ny]) = psi(:,:,[-nxx+1,nxx+1],[-nyy,nyy,ny]) - ...

通过考虑列表-nxx,-nyy, -nxx, nyy,等的所有组合有效地完成了我所需要的工作.

which effectively does what I need by taking into account all the combinations of the lists -nxx,-nyy, -nxx, nyy, etc.

但是,我需要的索引列表比[-nxx,nxx],[-nyy,nyy]大得多.我真的需要类似[-nxx,nxx,-nxx1,nxx1,-nxx2,nxx2,-nxx3,nxx3], [-nyy,nyy,-nyy1,nyy1,-nyy2,nyy2,-nyy3,nyy3]等的东西,其中nxx = nx/2, nxx1 = nx/4, nxx2 = nx/8, nxx3 = nx/16等.

However the list of indices I need is much bigger than just [-nxx,nxx],[-nyy,nyy]. I really need something like [-nxx,nxx,-nxx1,nxx1,-nxx2,nxx2,-nxx3,nxx3], [-nyy,nyy,-nyy1,nyy1,-nyy2,nyy2,-nyy3,nyy3] etc where nxx = nx/2, nxx1 = nx/4, nxx2 = nx/8, nxx3 = nx/16 etc.

有没有一种方法可以有效地做到这一点?例如,我可以只定义一个变量,例如:

Is there a way I can do this efficiently? For example, can I just define a single variable such as :

integer : Listx, Listy

   Listx = [-nxx,nxx,-nxx1,nxx1,-nxx2,nxx2,-nxx3,nxx3]
   Listy = [-nyy,nyy,-nyy1,nyy1,-nyy2,nyy2,-nyy3,nyy3]

然后有类似的东西

grad(:,:,Listx,Listy) = psi(:,:,Listx+1,Listy) - ...

我确实尝试过这样做,但是将Listx,Listy定义为整数似乎会带来问题.我尝试如下:

I did try doing this, but defining Listx, Listy as integers seems to be giving problems. I tried as follows:

Integer :: Listx, Listy

   Listx = [-nxx,nxx,-nxx1,nxx1,-nxx2,nxx2,-nxx3,nxx3]
   Listy = [-nyy,nyy,-nyy1,nyy1,-nyy2,nyy2,-nyy3,nyy3]

但是在编译时,Fortran告诉我不兼容的等级0,并且分配给..."

but then upon compiling Fortran tells me that "Incompatible ranks 0 and in assignment at ..."

如何正确定义?谢谢

推荐答案

如注释中所述,您在数组的声明中缺少dimension属性:

As said in the comments, you are missing the dimension attribute in the declaration of the arrays:

Integer :: Listx(8), Listy(8)

这应该可以解决您的问题.任何结果为rank-1数组的表达式都可以用作向量下标索引器.

This should solve your problem. Any expression that results to a rank-1 array is allowed as a vector subscript indexer.

这篇关于通过正确定义索引列表来提高代码效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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