Generate sequence array in fortran

Is there an array built into Fortran containing a sequence of numbers from a to b similar to python range()

 >>> range(1,5) [1, 2, 3, 4] >>> range(6,10) [6, 7, 8, 9] 

?

+7
source share
2 answers

No no.

However, you can initialize the array with a constructor that does the same thing,

 program arraycons implicit none integer :: i real :: a(10) = (/(i, i=2,20, 2)/) print *, a end program arraycons
program arraycons implicit none integer :: i real :: a(10) = (/(i, i=2,20, 2)/) print *, a end program arraycons 
+21
source

If you need to support floating point numbers, here is a Fortran routine similar to linspace in NumPy and MATLAB.

 ! Generates evenly spaced numbers from 'from' to 'to' (inclusive). ! ! Inputs: ! ------- ! ! from, to : the lower and upper boundaries of the numbers to generate ! ! Outputs: ! ------- ! ! array : Array of evenly spaced numbers ! subroutine linspace(from, to, array) real(dp), intent(in) :: from, to real(dp), intent(out) :: array(:) real(dp) :: range integer :: n, i n = size(array) range = to - from if (n == 0) return if (n == 1) then array(1) = from return end if do i=1, n array(i) = from + range * (i - 1) / (n - 1) end do end subroutine 

Using:

 real(dp) :: array(5) call linspace(from=0._dp, to=1._dp, array=array) 

Prints an array

 [0., 0.25, 0.5, 0.75, 1.] 

Here dp is

 integer, parameter :: dp = selected_real_kind(p = 15, r = 307) ! Double precision 
+1
source

Source: https://habr.com/ru/post/1335554/


All Articles