2014-11-05 94 views
1

我正在使用fortran 90,并且希望计算出现数量时,两个数字出现在数组中。如何计算fortran中矩阵中的数字的出现?

flag=0 
    q=0 
    do k=1,ncolumns 
     if (conn(m,k)==i .and. conn(m,k)==l) flag=1 
    enddo 
    if (flag==1) q=q+1 
    write (*,*) q 

这里,conn(m,k)是矩阵,由m行和k列组成。我想读conn(m,k),并计算当conn(m,k)中包含数字i和l时发生的次数。我知道上面的代码不会工作,因为它只打印出0,因为如果循环有问题。但我不能用'.or'。因为我希望计数当我和l都包含在conn(m,k)中时。我如何检查数字我和我是否包含在conn?

我修改了上面像

ncolumns=2 
    flag=0 
    q=0 
    do k=1,ncolumns 
     !!!if (conn(m,k)==i .and. conn(m,k)==l) flag=1 
     if (((conn(m,1)==i).and.(conn(m,2)==l)).or.((conn(m,1)==l).and.(conn(m,2)==i))) flag=1 
    enddo 
    if (flag==1) q=q+1 
    write (*,*) q 

也能正常工作的代码,但你可以看到,这个代码是荒谬的,因为我需要手动定义K,特别是当“ncolumns”是庞大的数字。我如何用索引来做到这一点?

同样,如何检查2个或更多的具体数字是否包含在矩阵中,例如fortran中的conn(m,k)?谢谢。

+0

@HighPerformanceMark第一种可以更紧密。 'conn'是一个矩阵,我想知道'conn'有多少行同时有2个或更多的数字,比如3和12。并计算它的发生。例如,如果conn中有3行共有两个元素(如3和12),则打印的q应该是3. – exsonic01 2014-11-05 16:43:05

+0

@HighPerformanceMark第二个示例代码的'ncolumns = 2'就是示例。实际上,conn是巨大的矩阵。它是5000行×15列的矩阵,由众多的数据块组成 – exsonic01 2014-11-05 16:48:45

回答

0

像这样的东西应该做你想要什么:

nums = [2,12,-4,99] ! an array of the numbers you're looking for 
    q = 0    ! the count of rows containing all the numbers in nums 

    DO ix = 1, SIZE(conn,1)  ! the number of rows in conn 
    nmatches = 0    ! the number of elements of nums found in conn(ix,:) 
    DO jx = 1, SIZE(nums) 
     IF(ANY(conn(ix,:)==nums(jx))) nmatches = nmatches+1 ! figure this out yourself 
    END DO 
    ! if there are as many matches in this row as there are elements in nums, add 1 to q 
    IF(nmatches==SIZE(nums)) q = q+1  
    END DO 
+0

谢谢,但我无法理解这个代码....哪里来的匹配,什么是匹配的意义?有'不匹配'和'匹配',但我无法弄清楚这两个变量的含义。另外,我是否需要制作新的〜d阵列?我可以直接将i和l或a和b与矩阵'conn'进行比较吗? – exsonic01 2014-11-05 17:34:05

+0

'matches'是个错误,应该是'nums'。而'nums'只是一个包含你正在寻找的数字的数组。我也编辑过。 – 2014-11-05 21:41:27

0

从评论:“如果有3条线路连接中其中有两个元素(如3和12)一起,印刷Q值应该3" 。 如果您有Fortran95(我忘了它是否在90规格中)或更高版本,您可以使用单循环来做到这一点。 下面是一个例子:

Program Test_Count 

    Implicit None 

    Real(Kind=8), Dimension(3) :: nums = (/-2.0_8 , -3.0_8 , -4.0_8/) 
    Real(Kind=8), Dimension(4,4) :: test 
    Logical, Dimension(4) :: Mask 
    Integer :: i,j,NumberOfLines 

    ! Fill test 
    Do i = 1,4 
    Do j = 1,4 
     test(i,j) = -4.0_8 + (j -1) 
    End Do 
    End Do 

    ! Count the row that have all the nums in them 
    Mask = any(test == nums(1),2) 
    Do i = 2,3 
    Mask = Mask .and. any(test == num2(i),2) 
    End Do 
    NumberOfLines = count(Mask) 

    Write(*,*) NumberOfLines ! Prints out 4. 

End Program Test_Count