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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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.
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)
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!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.