Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array with different lengths

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.

like image 800
user1543042 Avatar asked Aug 19 '13 14:08

user1543042


Video Answer


2 Answers

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))
like image 199
High Performance Mark Avatar answered Jan 29 '23 22:01

High Performance Mark


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

like image 26
agentp Avatar answered Jan 29 '23 22:01

agentp