Convert an array of logical type to an array of integer/double type -
i using silverfrost ftn95 and, since not expert, need create function takes input array of logical variables , returns array of integer variables, 0 false , 1 true. wrote simple code semplify how tried implement it:
program main logical, dimension(2,1) :: integer, dimension(2,1) :: b integer, dimension(2,1) :: toint a(:,1)=.false. b=toint(a) write(*,*)b end program function toint(log) result(val) logical, dimension(2,1), intent(in) :: log integer, dimension(2,1) :: val i=1,2 if (log(i,1)) val(i,1) = 1 else val(i,1) = 0 end if end end function
this code gives me error: integer expression expected in array bounds subscript, variable 'a' not have integer type (at line "b=toint(a)"), , can't find error is. suggestions or other ways solve problem helpful. thanks
the error message comes because in program main
you've declared toint
array, statement toint(a)
interpreted attempt index array using logical a
. think you've declared toint
external function returns integer array, you've not given compiler enough information make connection function definition.
you fix removing misleading declaration of toint
program, moving line end program
end of source file, , inserting line contains
have end program
. these steps make toint
internal , compiler take care of matching calls function itself.
but think there 3, possibly more, better ways, have.
one write along lines of
integer, dimension(x,y) :: a,b,r logical, dimension(x,y) :: m ! set elements of m wish = 1 b = 0 r = merge(a,b,m)
which assign r
values a
m
.true.
, b
m
.false.
doesn't matter x
, y
are, array arguments merge
conformable. should relatively easy turn function repeated use.
secondly, use where
statement, perhaps this
r = 0 ! elements set 0 where(m) r = 1 ! m true, r set 1
this approach dispenses a
, b
.
thirdly investigate writing elemental
function operates on scalars , on arrays of rank. i'll leave 1 exercise. requires modification function have, operates on scalars , not on fixed-size arrays. third approach best - straightforward, flexible, easiest program.
Comments
Post a Comment