Suppose during the execution of a program you get the following output file:
1 2
2 2
3 1
.
.
.
n 5
and the first line tells you that you need a matrix say A(2,k)
, the second line a matrix B(2,k)
, the third line a matrix C(1,k)
,..., and the last line a matrix S(5,k)
, where n and k are already known.
How do you allocate the matrices A,B,C
,...,S
? If the entries of second column of the file where the same e.g 5, I could allocate one matrix, i.e:
real, allocatable :: mymat(:,:,:)
and after reading the output file I would allocate:
allocate(mymat(n,5,k))
and that would be the end of the story. In this case, I can't do that, since the second dimension varies, so I need n
different matrices. Any ideas?
I assume that the last line means a S(5,k)
matrix, not S(n,k)
as you wrote?
Assuming you know the maximum value in the second column, say smax
, your solution real, allocatable :: mymat(:,:,:)
then allocate(mymat(n,smax,k))
is perfectly acceptable if you accept occupying more memory than needed. The first submatrix will be mymat(1,1:2,:)
, the second submatrix will be mymat(2,2:2,:)
, the third one maymat(3,1:1,:)
, and so on... Note that it would be better to assign the matrix number to the 3rd dimension so that each submatrix is contiguous in memory, i.e. allocate(mymat(smax,k,n))
Otherwise, as suggested by @IanBush, you may define a derived type:
type array_t
real, allocatable :: a(:,:)
end type
type(array_t) :: mymat(:)
allocate( mymat(n) )
allocate( mymat(1)%a(2,k) )
allocate( mymat(2)%a(2,k) )
allocate( mymat(3)%a(1,k) )
...
(of course the individual allocates would be in a loop)