2014-11-05 41 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