问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/21568652/fortran-array-inside-array