Multidimensional array with different lengths

谁都会走 提交于 2019-12-27 15:54:10

问题


I am trying to make an array with different lengths in a second dimension e.g.:

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

Is this possible? I've spent a fair amount of time looking but cannot find out either way.


回答1:


Yes and no. First the no:

Proper arrays in Fortran, such as those declared like this:

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

or like this

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

are regular; for each dimension there is only one extent.

But, if you want to define your own type for a ragged array you can, and it's relatively easy:

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

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

With this sort of approach you can allocate the elements of each of the vectors to a different size. For example:

type(ragged_array) :: ragarr
...
allocate(ragarr%vectors(5))
...
allocate(ragarr%vectors(1)%elements(3))
allocate(ragarr%vectors(2)%elements(4))
allocate(ragarr%vectors(3)%elements(6))



回答2:


looking at the first answer, it seems there is no need to create the derived type vector which is really just an allocatable integer array:

    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))

this makes the notation a little less cumbersome..



来源:https://stackoverflow.com/questions/18316592/multidimensional-array-with-different-lengths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!