通过派生类型数组 [英] Pass derived type as array
问题描述
在Fortran语言,可以在阵列上运行,但一个人如何可以把一个派生类型的指数作为数组太大的一部分? code会解释什么,我想要做的最好的:
In Fortran, one can operate on arrays, but how can one treat the indices of a derived type as part of an array too? Code would explain what I want to do best:
type mytype
integer :: b(3,3)
real :: c(4)
endtype
integer :: a(3,3)
real :: d(2,4)
type(mytype) :: mat(2)
!do stuff so that 'mat' gets values
....
!usually one does this
a = matmul(mat(1)%b, transpose(mat(2)%b))
!multiplying two 3x3 matrices
!but how does one do this? Note the "array"
d = matmul(mat(:)%c, mat(:)%c)
我假定最后一行类似于一个2x4的矩阵被乘以本身。然而,当我尝试编译,gfortran抱怨
I assumed that the final line is analogous to a 2x4 matrix being multiplied with itself. However, when I try to compile, gfortran complains
错误:有非零秩的两个或多个部分引用,不得指定
Error: Two or more part references with nonzero rank must not be specified
这是可能用Fortran办?
Is this possible to do in Fortran?
推荐答案
您希望编译器把垫(:)%C
为2×4矩阵?它不这样的。 垫
和 C
是不同的对象和他们的等级不合并成一个单一的阵列。 垫
是一个用户定义的类型和 C
是一个真正的矩阵。仅仅因为你只使用 C
的-component 垫
并不意味着编译器会推动<$ C $ ç> C 到一个更高维实阵列,根据垫
。
You want the compiler to regard mat(:)%c
as a 2 x 4 matrix? It doesn't work that way. mat
and c
are different objects and their ranks don't merge into a single array. mat
is a user-defined type and c
is a real matrix. Just because you are only using the c
-component of mat
doesn't mean the compiler will promote c
to a higher dimensional real array, based on the dimension of mat
.
您可以通过创建一个新的数组 X = [垫(1)%C,垫(2)%C]
。你可以使用重塑
来控制形状。
You could create a new array via X = [ mat(1)%c, mat(2)%c ]
. You could use reshape
to control the shape.
这篇关于通过派生类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!