4

I am trying to create an array in Fortran similar to a cell in MATLAB.

Basically (for example) I am trying to create an array X(10) where the element X(1) is an array with dimension (20,2), X(2) is an array with dimension (25,2), etc.

How can I do this?

francescalus
  • 30,576
  • 16
  • 61
  • 96
Gvilla1000
  • 41
  • 2
  • 2
    You should have a read about MATLAB [cell arrays](http://www.mathworks.com/help/matlab/cell-arrays.html). They will let you do what you're attempting. – MrAzzaman Feb 05 '14 at 04:29
  • 3
    Note the question isn't about MATLAB - it is about how to do something in Fortran. That something has been quite clearly specified through analogy. The natural solution to the problem is also a reasonably direct consequence of language design, rather than "opinion", so I don't understand the rationale for the close votes. – IanH Feb 05 '14 at 11:17

1 Answers1

6

The equivalent for your specific case is achieved using a derived type, that contains a single component. The cell array corresponds to an array of that derived type, the arrays that sit inside each element of the cell array are then the array components of each array element.

Something like:

TYPE Cell
  ! Allocatable component (F2003) allows runtime variation 
  ! in the shape of the component.
  REAL, ALLOCATABLE :: component(:,:)
END TYPE Cell

! For the sake of this example, the "cell array" equivalent 
! is fixed length.
TYPE(Cell) :: x(10)

! Allocate components to the required length.  (Alternative 
! ways of achieving this allocation exist.)
ALLOCATE(x(1)%component(20,2))
ALLOCATE(x(2)%component(25,2))
...
! Work with x...

Cells in MATLAB have much more flexibility than given by the specific type above (this is really more akin to the MATLAB concept of a structure). For something that approaches the flexibility of a cell array you would need to use an unlimited polymorphic component and further intermediate type definitions.

IanH
  • 21,026
  • 2
  • 37
  • 59
  • Thanks a lot. This surely cleared the mess I had in my head. One quick question though...is it necessary to deallocate the arrays once they are used or are they automatically removed from memory once the program reaches the end? – Gvilla1000 Feb 06 '14 at 05:10
  • It is not necessary (bar obscure cases not relevant here). Any allocatable thing (including allocatable components) local to a procedure that doesn't have the SAVE attribute gets deallocated when the procedure finishes. – IanH Feb 06 '14 at 06:41