2

Let's say I have an array of dimensions declared like this:

integer, dimension(5) :: dims
dims = (/ 5, 6, 7, 8, 9 /)

How can I most simply use this array to allocate another array, using the elements of dims to specify the size of the respective dimensions? Say the second array is declared like this:

real, dimension(:,:,:,:,:), allocatable :: dset

Why can't I do the following?

allocate (dset(dims(:)))

I get Error: Rank mismatch in array reference when I attempt to compile.

I realize that I can do this:

allocate (dset(dims(1), dims(2), dims(3), dims(4), dims(5)))

But I'm looking for something more easily extensible.

pattivacek
  • 5,617
  • 5
  • 48
  • 62

1 Answers1

2

You cannot write allocate(dset(dims(:))) for exactly the reason the compiler gives: they have different ranks. If you were to print shape(dims), you would see 5 on-screen; if you were to print shape(dset), you would see either 0 0 0 0 0 or 5 6 7 8 9 (depends if you allocated it or not); dims is a rank-1 array, dset is a rank-5 array.

So pretty much the only way to allocate an allocatable is via the explicit method that you feel is inextensible.

Kyle Kanos
  • 3,257
  • 2
  • 23
  • 37
  • Is there really no way to get array elements into the appropriate list format? I realize that it would be kind of "meta" and I wasn't really expecting there to be such a shortcut, but I was hoping there was a trick I was unaware of. – pattivacek Jul 22 '13 at 19:28
  • 1
    There *is* an alternative but it requires two things: (1) Intel Fortran compiler and (2) an already-allocated array of the same dimensions. If you have both of these already you can use `allocate(dset,mold=already_set_array)` and get your array full of zeros. Outside of that, the standard way is the **only** way. – Kyle Kanos Jul 22 '13 at 19:34
  • Fortran syntax is inherently inflexible. I used to try and force the language to be more elegant but I've given up and am now more pragmatic. If you want elegance use Python or Mathematica. – bdforbes Jul 23 '13 at 20:02
  • Elegance is in the eye of the beholder. Python is fairly inelegant, IMO, while Fortran is beautiful. Besides that, Python is horrendously slow when compared to Fortran (really, **any** _interpreted_ language is going to be slow when compared to any other _compiled_ language) – Kyle Kanos Jul 23 '13 at 20:18
  • I don't find Fortran's relative inflexibility to be an issue. I was just looking for a better way to solve my problem. For now, I'm going to go ahead and accept your answer, although I'm still going to hold out hope that there is an easier way without depending on Intel! – pattivacek Jul 24 '13 at 14:07
  • It is not really an Intel-only thing for `MOLD`. It is really a Fortran 2008 item that has (to my knowledge) only been added to Intel's compiler. I imagine it is in everyone else's "TO DO" list (as with a lot of other 2003/2008 additions). – Kyle Kanos Jul 24 '13 at 16:13