array of arrays in fortran
Asked Answered
E

3

8

I am trying to define a array of arrays. I have defined:

  integer,dimension(2,2):: & 
    x=reshape(source= (/0,1,1,0/),  shape=(/2,2/)), & 
    y=reshape(source= (/1,0,0,1/),  shape=(/2,2/)), & 
    z=reshape(source= (/1,1,1,1/),  shape=(/2,2/)) 

I want to define an array, say, s(3), of which, (x/y/z) are components, i.e.

s(1)=x 
s(2)=y 
and s(3)=z

how can I achieve that?

Exorbitant answered 29/10, 2013 at 21:23 Comment(0)
L
8

The simplest approach might be to define s as a rank-3 array, perhaps

integer, dimension(3,2,2) :: s

and then you can write statements such as

s(1,:,:) = x
s(2,:,:) = y
...

This is the 'natural' way to implement an array of arrays in Fortran. An alternative, which might appeal to you more would be something like:

type :: twodarray
   integer, dimension(2,2) :: elements
end type twodarray

type(twodarray), dimension(3) :: s

s(1)%elements = x

If you don't like the wordiness of s(1)%elements = x you could redefine the operation = for your type twodarray, I don't have time right now to write that code for you.

Lauber answered 29/10, 2013 at 21:56 Comment(0)
S
6

You can always use pointers (in Fortran 95)

program main
  implicit none

  type :: my_type
     integer, pointer :: my_size(:)      ! F95
     !integer, allocatable :: my_size(:) ! F95 + TR 15581 or F2003
  end type my_type

  type(my_type), allocatable :: x(:)

  allocate(x(3))

  allocate(x(1)%my_size(3))
  allocate(x(2)%my_size(2))
  allocate(x(3)%my_size(1))

  print*, x(1)%my_size
  print*, x(2)%my_size
  print*, x(3)%my_size

  deallocate(x(3)%my_size, x(2)%my_size, x(1)%my_size)
  deallocate(x)

end program main

It will print

       0           0           0
       0           0
       0
Solvable answered 31/10, 2013 at 4:3 Comment(0)
N
0

The following is a complete program that uses “(re-)allocation on assignment”, which makes dynamic arrays be more like variables in a dynamically typed language.

program main
  implicit none
  integer,dimension(2,2):: & 
    x=reshape(source= (/0,1,1,0/),  shape=(/2,2/)), & 
    y=reshape(source= (/1,0,0,1/),  shape=(/2,2/)), & 
    z=reshape(source= (/1,1,1,1/),  shape=(/2,2/))

  type :: my_type
     integer, allocatable :: component(:,:)
  end type my_type

  type(my_type) :: s(3)

  s(1)%component=x
  s(2)%component=y
  s(3)%component=z

  print*, s(1)%component
  print*, s(2)%component
  print*, s(3)%component
end program main

It outputs:

           0           1           1           0
           1           0           0           1
           1           1           1           1
Norenenorfleet answered 2/6, 2023 at 6:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.