Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

fortran - Concise notation for inheriting size from other array?

In my code, I have a subroutine that takes a 5th-rank array as argument and uses a local variable, which is a 4-th rank array sharing the first 4 indices.

I'm trying to find a more concise way to express the size declaration in

subroutine mysub(momentum)
  complex, intent(in) :: momentum(:,:,:,:,:)
  complex :: prefactor( &
      & size(momentum,1), size(momentum,2), size(momentum,4) &
      & size(momentum,5) )
  ...
end subroutine mysub

The verbosity of the size declaration harms readability, especially when variable names are even longer than here.

If this was octave/matlab I'd pre-allocate prefactor by writing

prefactor = zeros(size(momentum)([1 2 4 5]))

Does Fortran 90 support something similarly concise? I know that it could be solved using preprocessor macros, such as

#define XSIZE2(array,a,b) SIZE(array,a), SIZE(array,b)
#define XSIZE3(array,a,b,c) SIZE(array,a), SIZE(array,b), SIZE(array,c)
#define XSIZE4(array,a,b,c,d) SIZE(array,a), SIZE(array,b), SIZE(array,c), SIZE(array,d)

but introducing such definitions would probably harm the readability more than it helps.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fortran 2008 added the mold specifier to the allocate statement. If you have access to a compiler that supports this feature, you can try

program main

  implicit none

  integer :: a(2,3,4,5,6)
  integer, allocatable :: b(:,:,:,:)

  print *, shape(a)

  allocate(b, mold=a(:,:,:,:,1))
  print *, shape(b)

end program main

This snippet worked with Intel Fortran 2016, Update 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...