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.
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))
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With