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

这一生的挚爱 提交于 2019-12-01 12:19:57

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!