Fortran array with dynamic size, as easy the R function seq()

后端 未结 2 1092
渐次进展
渐次进展 2021-01-16 05:41

I would like to write Fortran code that works like the R function seq(). E.g.:

x <- seq(0,1,0.1)

will give the vector

x          


        
相关标签:
2条回答
  • 2021-01-16 05:49

    A simple implementation, if you really wanted the function, not wanting to always compute the n by hand. May need some clarification of the upper bound.

    print *,seq(1.,10.,0.1)
    
    contains
    
    function seq(from, to, step)
      real, allocatable :: seq(:)
      real, intent(in) :: from, to, step
    
      allocate(seq(0:int((to - from)/step)))
      do i = 0, size(seq)
        seq(i) = from + i * step
      end do
    end function
    
    end
    

    Regarding your program, when you use the fretures the compiler has, the backtrace would be much more helpful. Your resize_array should probably have tmp_arr(1:new-1)=t. The move_alloc() subroutine could make it little bit shorter.

    0 讨论(0)
  • 2021-01-16 05:53

    Fortran 2003 has (re-)allocation upon assignment for allocatable arrays, and the program

    program xgrid
    implicit none
    real, allocatable :: x(:)
    integer           :: i,n
    do n=5,10,5
       x = 0.1*[(i,i=0,n)]
       write (*,"('x =',100(1x,f0.1))") x
    end do
    end program xgrid
    

    compiled with gfortran 4.8.0, shows a Fortran one-liner equivalent to seq(), giving output

    x = .0 .1 .2 .3 .4 .5

    x = .0 .1 .2 .3 .4 .5 .6 .7 .8 .9 1.0

    0 讨论(0)
提交回复
热议问题