是否可以在Fortran中將矩陣聲明爲派生類型?例如,可以做些什麼以致於致電是否可以在Fortran中將矩陣聲明爲派生類型?
class(four_by_four_matrix) :: A
call A%inv
是否有效?其中inv
被宣佈爲four_by_four_matrix
的程序?
是否可以在Fortran中將矩陣聲明爲派生類型?例如,可以做些什麼以致於致電是否可以在Fortran中將矩陣聲明爲派生類型?
class(four_by_four_matrix) :: A
call A%inv
是否有效?其中inv
被宣佈爲four_by_four_matrix
的程序?
問題的答案「可能嗎?」是的,這是可能的。只要把一個二維數組到你喜歡的類型:
type four_by_four_matrix
real(rp) :: arr(4,4)
contains
procedure :: inv => four_by_four_matrix_inv
end type
contains
subroutine four_by_four_matrix_inv(self)
class(four_by_four_matrix), intent(inout) :: self
....
!somehow invert self%arr
end subroutine
end module
...
type(four_by_four_matrix) :: A
call A%inv
如果您需要更多的細節,你必須做出一個問題與您的實際細節問題。
BTW類型綁定過程和class
關鍵字在Fortran 2003中引入。注意,您不一定需要使用class
,如果變量不是多態,也可以使用type(four_by_four_matrix)
。
Vladimir F給出an approach使用在Fortran 2003中引入的類型綁定過程,並且還對class
的多態聲明發表評論。
這個答案假設你有,如問題所示,一個四乘四矩陣,或至少在編譯時已知的大小。在更廣泛的用途中,人們可能想要推廣。然後,值將使組件數組可分配(確保它以某種方式分配,並注意這不是Fortran 90/95)。
或者,Fortran 2003還引入了的概念參數化派生類型。在這裏,很像一個字符長度可變的想法一個可能的長度,參數化派生類型:
type square_matrix(n)
integer, len :: n
real matrix(n,n)
end type square_matrix
聲明的變量,比如
type(square_matrix(4)) A ! Like type(four_by_four_matrix), perhaps
type(square_matrix(8)) B ! Like type(eight_by_eight_matrix), perhaps
人們可以甚至推遲長這種類型的變量
type(square_matrix(:)), allocatable :: A, B
integer q
q = ... ! Something run-time, perhaps.
allocate(square_matrix(q) :: A)
B = square_matrix(q)(matrix) ! Constructor using a matrix value
類型結合的程序的行爲上的任意參數化的類型,使用假定長度語法:
subroutine inv(sm)
class(square_matrix(*)), intent(inout) :: sm
...
end subroutine inv
一個幾乎完整的例子如下。
module matrix_mod
implicit none
type square_matrix(n)
integer, len :: n
real matrix(n,n)
contains
procedure inv
end type square_matrix
contains
subroutine inv(sm)
class(square_matrix(*)), intent(inout) :: sm
! Some inv stuff, but as a placeholder
print '("Called inv with a ",I0,"-by-",I0," matrix")', sm%n, sm%n
end subroutine inv
end module matrix_mod
use matrix_mod
implicit none
type(square_matrix(4)) A
! Establish A%matrix somehow, perhaps with a structure constructor
call A%inv()
end
當然,不限於矩形矩陣:可以使用多個參數。此外,我也跳過了種類參數化的可能性。
我正在考慮寫這些,因爲這種用法很自然。但我仍然沒有準備好在實踐中使用它,因爲gfortran的支持仍然不適用於大多數人使用的版本。 –
我沒有注意到,即使在最近的gfortran版本中也有支持(但我沒有跟上),所以是的,這是未來和更廣泛受衆的答案。在這個PDT網站上很少有例子,可能是因爲有限的編譯器支持,這似乎是一個簡單而自然的例子。 – francescalus