将派生类型作为数组传递
在 Fortran 中,可以对数组进行操作,但如何将派生类型的索引也视为数组的一部分呢?代码将解释我最想做的事情:
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 抱怨
错误:不得指定两个或多个具有非零等级的零件引用
这可以在 Fortran 中执行吗?
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)
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
Is this possible to do in Fortran?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将非方阵与其自身相乘。你必须转置其中之一。
您还可以混合实数和整数。您的矩阵应该是实数,并且您的结果是整数。
可以使用小型 FORTRAN STYLE hack 来引用矩阵(等价和序列,假设默认整数和实数的存储大小相同)。这个可以编译:))))
You can't multiply nonsquare matrices by themselves. You have to transpose one of them.
You also mix reals and integers. Your matrices are supposed to be real and your result is integer.
It's possible to reference the matrix with a small FORTRAN STYLE hack (equivalence and sequence, assuming same storage size for default integer and real). This one compiles :))))
您希望编译器将 mat(:)%c 视为 2 x 4 矩阵吗?事实并非如此。
mat
和c
是不同的对象,它们的等级不会合并到单个数组中。mat
是用户定义的类型,c
是实数矩阵。仅仅因为您仅使用mat
的c
组件并不意味着编译器会将c
提升为更高维的实数数组,基于在mat
的维度上。您可以通过
X = [ mat(1)%c, mat(2)%c ]
创建一个新数组。您可以使用reshape
来控制形状。You want the compiler to regard
mat(:)%c
as a 2 x 4 matrix? It doesn't work that way.mat
andc
are different objects and their ranks don't merge into a single array.mat
is a user-defined type andc
is a real matrix. Just because you are only using thec
-component ofmat
doesn't mean the compiler will promotec
to a higher dimensional real array, based on the dimension ofmat
.You could create a new array via
X = [ mat(1)%c, mat(2)%c ]
. You could usereshape
to control the shape.