n在fortran90中嵌套for循环 [英] n nested for loops in fortran90

查看:553
本文介绍了n在fortran90中嵌套for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些有关此的主题,但是我不太认为它可以回答我的问题.如果确实如此,那么请引导我进入正确的主题,我一定会再看一遍.

i have read some topics on this, but i don't quite think it answers my question. if it does then please direct me to the correct topic and i will definitely look again.

这是我的问题:

我想编写一个for循环,该循环将遍历数组长度为'n'的数组的所有可能组合.

i want to write a for loop which will cycle through every possible combination of an array where the array is of length 'n'.

也就是说,如果n = 2,那么我的for循环将是

that is, if n = 2 then my for loop would be

do i1 = 1,2
    do i2 = 1,2
         ! do stuff here
    enddo
enddo

如果n = 3,则我的数组看起来像

while if n = 3 then my array would look like

do i1 = 1,3
    do i2 = 1,3
         do i3 = 1,3
             ! do stuff here
         enddo
    enddo
enddo

,依此类推.我该如何编写一个例程,该例程只需输入一个变量"n"即可自动完成此操作?

and so on. how would i go about writing a routine which would do this automatically by simply an an input variable 'n'?

推荐答案

如果您写出索引,则您拥有的是以n为底的n位数字(几乎-偏移量为1,因为您使用的是1-基于fortran的索引).而您要的是该数字可以取的所有可能的值.

if you write out the indices, what you have is an n-digit number in base n (almost - there's an offset of 1 because you are using 1-based indices in fortran). and what you are asking for is every possible value that number can take.

换句话说,如果为了简单起见我们暂时使用基于0的索引,那么您将:

in other words, if we use 0-based indices for a moment for simplicity, you have:

  • n = 2,值= 00,01,10,11(从0到3的二进制计数)
  • n = 3,值= 000,001,002,010,011,012,020,021,022,100,101,102,110,111,112,120,121,122,200,201,202,210,211,212,220,221,222(三进制(?)从0到26计数)

所以您要问的是一般情况下该如何做.

so what you are asking is how to do this in the general case.

,您可以使用数组来保存n位数字,从[0,0 .... 0]开始.然后,在"while"循环内(它将替换n个嵌套的for循环),尝试增加最右边的条目(数字).如果等于n,则返回零并向左递增.一旦您设法增加一个值而没有达到n,那么您就完成了,可以将数字用作索引.

and you can do that by using an array to hold the n digits, starting at [0,0....0]. then, within a "while" loop (which will replace your n nested for loops), try to increment the right-most entry (digit). if that is equal to n, then go back to zero and increment to the left. once you manage to increment a value without reaching n then you are "done" and can use the numbers as your indices.

这很简单-每次只需加1.

it's pretty simple - you're just adding 1 each time.

然后,对于fortran基于1的索引,将1加到每个数字上.换句话说,将上面的内容更改为以1s开头,然后在n + 1处向左移动.

then, for fortran's 1-based indexing, add 1 to each digit. in other words, change the above to start with 1s and move left at n+1.

例如,对于n = 4:

for example, for n=4:

  • 以[1,1,1,1]开头
    • 做内循环动作
    • start with [1,1,1,1]
      • do your inner loop action
      • 做内循环动作
      • 做内循环动作
      • 做内循环动作
      • 做内循环动作
      • 做内循环动作

      这篇关于n在fortran90中嵌套for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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