Fortran中的数组数组

8

我想定义一个二维数组。 我已经定义了:

  integer,dimension(2,2):: & 
    x=reshape(source= (/0,1,1,0/),  shape=(/2,2/)), & 
    y=reshape(source= (/1,0,0,1/),  shape=(/2,2/)), & 
    z=reshape(source= (/1,1,1,1/),  shape=(/2,2/)) 

我想定义一个数组,比如 s(3),其中 (x/y/z) 是组成部分,即:
s(1)=x 
s(2)=y 
and s(3)=z

我该如何实现这个目标?
3个回答

8
最简单的方法可能是将`s`定义为一个3维数组,例如:
integer, dimension(3,2,2) :: s

之后,您可以编写诸如以下语句:

s(1,:,:) = x
s(2,:,:) = y
...

这是在Fortran中实现数组的“自然”方式。另一种可能更适合您的选择是类似于以下内容:
type :: twodarray
   integer, dimension(2,2) :: elements
end type twodarray

type(twodarray), dimension(3) :: s

s(1)%elements = x

如果您不喜欢s(1)%elements = x这个过于冗长的表达方式,您可以重新定义类型twodarray的操作=。但我现在没有时间为您编写代码。


5

你总是可以使用指针(在Fortran 95中)

program main
  implicit none

  type :: my_type
     integer, pointer :: my_size(:)      ! F95
     !integer, allocatable :: my_size(:) ! F95 + TR 15581 or F2003
  end type my_type

  type(my_type), allocatable :: x(:)

  allocate(x(3))

  allocate(x(1)%my_size(3))
  allocate(x(2)%my_size(2))
  allocate(x(3)%my_size(1))

  print*, x(1)%my_size
  print*, x(2)%my_size
  print*, x(3)%my_size

  deallocate(x(3)%my_size, x(2)%my_size, x(1)%my_size)
  deallocate(x)

end program main

它将会打印出来。
       0           0           0
       0           0
       0

0
以下是一个完整的程序,它使用“赋值时重新分配”技术,使动态数组更像动态类型语言中的变量。
program main
  implicit none
  integer,dimension(2,2):: & 
    x=reshape(source= (/0,1,1,0/),  shape=(/2,2/)), & 
    y=reshape(source= (/1,0,0,1/),  shape=(/2,2/)), & 
    z=reshape(source= (/1,1,1,1/),  shape=(/2,2/))

  type :: my_type
     integer, allocatable :: component(:,:)
  end type my_type

  type(my_type) :: s(3)

  s(1)%component=x
  s(2)%component=y
  s(3)%component=z

  print*, s(1)%component
  print*, s(2)%component
  print*, s(3)%component
end program main

它输出:

           0           1           1           0
           1           0           0           1
           1           1           1           1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接