2015-03-02 55 views
0

我是Fortran的新手,我想要的是矩陣的大小取決於N是偶數還是奇數, 天真地,我會嘗試類似下面的內容,但是這不會編譯,如果我刪除if語句它可以正常工作,但是,在動態大小聲明後在fortran中定義數組

subroutine f(fMatrix,oMatrix,N) 
     implicit none; 
     integer,intent(in)::N 
     integer::d2 
     if(mod(N,2)==0) then ! if N is even then 1 type of size 
     parameter(d2=1) 
     else 
     parameter(d2=2) 
     endif 
     double precision,intent(in),dimension(N, d2):: fMatrix 
     double precision,intent(out),dimension(N, d2):: oMatrix 
     !do stuff here with fMatrix 
     oMatrix = fMatrix 
end subroutine f 

對此有什麼可能的解決方法?不會分配? 我正在使用f2py,所以任何具體的方式都會很方便。

回答

2

我覺得這是最接近你想要達到的目標:

subroutine f(fMatrix,oMatrix,N) 
    implicit none 
    integer,intent(in)         :: N 
    double precision,intent(in),dimension(N, mod(N,2)+1) :: fMatrix 
    double precision,intent(out),dimension(N, mod(N,2)+1) :: oMatrix 

    ! ... 
    oMatrix = fMatrix 
end subroutine 

我個人寧願以下解決方案之一:

  1. 由於兩個fMatrixoMatrix假參數並傳遞給子程序,可以使用assumed shape array specifications
subroutine f(fMatrix,oMatrix,N) 
    implicit none 
    integer,intent(in)       :: N 
    double precision,intent(in),dimension(:, :) :: fMatrix 
    double precision,intent(out),dimension(:, :) :: oMatrix 

    ! ... 
end subroutine 

現在調用程序需要指定數組的形狀。

  • 定義d2外部並把它傳遞到子例程,以及:
  • subroutine f(fMatrix,oMatrix,N, d2) 
        implicit none 
        integer,intent(in)       :: N, d2 
        double precision,intent(in),dimension(N, d2) :: fMatrix 
        double precision,intent(out),dimension(N, d2) :: oMatrix 
    
        ! ... 
    end subroutine 
    

    並調用子程序與:

    call f(fMatrix,oMatrix,N,mod(N,2)+1) 
    
    +0

    我明白你在說什麼,但是有沒有辦法從外面指定?因爲對於原始程序,我希望d2爲奇數,N爲偶數。我可以在函數本身傳遞參數並聲明數組,但是我想知道是否可以繞過這個 – Ars3nous 2015-03-02 14:30:56

    +0

    這可能會錯過一個重要的想法:顯式形狀僞參數數組的行爲與假設形狀僞參數數組的行爲與數種方式有很大不同。 – francescalus 2015-03-02 14:34:02

    +1

    在你的程序中的某一點,你必須決定你的陣列應該有多大。我的猜測是,你想用Python做到這一點,並將數組傳遞給Fortran代碼。如果你想在Fortran中這樣做,你可能需要'分配'數組或者使用自動分配。無論哪種方式,由於您將輸入傳遞給子例程並期望輸出,因此這些數組必須在調用子例程之前和之後存在。 – 2015-03-02 14:34:07