You can also try calmat (GitHub - hassaniriad/calmat: a Fortran Equation Parser Involving Matrix Operations). For your example, I can think of at least three ways to do this (depending on whether or not you are required to use a loop):
! Version 1: parse first the expresson "r = x^2 + 2*x", then evaluate in a do-loop
use calmat_m
implicit none
type (ind_t) :: indx, indr
integer(Ikind) :: i, handleId
real (Rkind), allocatable :: xx(:), res(:), r
xx = [ 1.0, 2.0, 3.0 ] ; allocate(res, mold = xx)
call calmat ( exprIn = "x = [] ; r = [] ;" ) !< a 1st call to calmat just to define in the
!< calmat workspace the involved variables
call calmat_inquire ( "x", indx ) !< get the Id of the variable x
call calmat_inquire ( "r", indr ) !< get the Id of the variable r
call calmat ( exprIn = "r = x^2 + 2*x ;", parseOnly = handleId ) !< parse the expression
do i = 1, size(xx)
call calmat_copy ( from = xx(i), to = indx ) !< Set x to xx(i)
call calmat ( evaluate = handleId ) !< Evaluate the exprssion
call calmat_copy ( from = indr, to = r ) !< Get the result in the intrinsic r
res(i) = r
end do
print*, "The result is (Version 1):"
print*,res
end
! Version 2: direct evaluation (using a for-loop in the expression)
use calmat_m
implicit none
real(Rkind), allocatable :: res(:)
call calmat ( exprIn = &
"x = [1.,2.,3.] ; r = zeros(x) ; for i = 1:size(x) ; r(i) = x(i)^2 + 2*x(i) ; end for" )
call calmat_moveAlloc ( from = 'r', to = res ) !< Get the result in the intrinsic res
print*, "The result is (Version 2):"
print*,res
end
! Version 3: direct evaluation (using a vectorial form)
use calmat_m
implicit none
real(Rkind), allocatable :: res(:)
call calmat ( exprIn = "x = [1.0, 2.0, 3.0] ; r = x.^2 + 2*x ; " ) !< Note the element-wise operation
call calmat_moveAlloc ( from = 'r', to = res ) !< Get the result in the intrinsci res
print*, "The result is (Version 3):"
print*,res
end
(Note: I have tested calmat only on linux and macOS (intel) with gfortran, ifort and nagfor. If anyone wants to try it on other platforms or compilers, I’d be very interested!)