具有不同长度的多维数组

时间:2013-08-19 14:41:19

标签: arrays multidimensional-array fortran

我试图在第二维中制作一个不同长度的数组,例如:

  A = 1 3 5 6 9
      2 3 2
      2 5 8 9

这可能吗?我花了相当多的时间看,但无论如何都找不到。

2 个答案:

答案 0 :(得分:19)

是和否。首先是否:

Fortran中的正确数组,例如声明为这样的数组:

integer, dimension(3,3,4) :: an_array

或者像这样

integer, dimension(:,:,:,:), allocatable :: an_array

是正规的;对于每个维度,只有一个范围。

但是,如果你想为一个参差不齐的数组定义你自己的类型,那就相当容易了:

type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

通过这种方法,您可以将每个elements的{​​{1}}分配给不同的大小。例如:

vectors

答案 1 :(得分:4)

查看第一个答案,似乎没有必要创建派生类型vector,它实际上只是一个可分配的整数数组:

    type ragged_array
    integer,allocatable::v(:)
    end type ragged_array
    type(ragged_array),allocatable::r(:)
    allocate(r(3))
    allocate(r(1)%v(5))
    allocate(r(2)%v(10))
    allocate(r(3)%v(15))

这使得符号变得不那么麻烦......