简体   繁体   中英

Fortran equivalent of python numpy.minimum

I am trying to re-write some python code in fortran, specifically the line

separation[a, :] = sum(np.minimum(1 - distances, distances) ** 2)

The important part being the use of np.minimum to take the element-wise minimum of two multi-dimensional arrays. Distances is a (3, N) array of N coordinates (x,y,z). I can't find a similar function in fortran, so I wrote my own using:

  do b = 1, N
    temp = 0.0
    do c = 1, 3
      if ((1 - distances(c, b)) .LE. distances(c, b)) then
        temp = temp + (1 - distances(c, b)) ** 2
      else
        temp = temp + (distances(c, b)) ** 2
      end if
    end do
    separation(a, b) = temp
  end do

Unsurprisingly this code is very slow, I am not very experienced in fortran yet so any recommendations as to improving this code or suggesting an alternative method would be greatly appreciated.

I thought perhaps a where statement might help, as the following code in python works

separation[a, :] = sum(np.where(1 - distances <= distances, (1 - distances), distances) ** 2)

But while fortran has where statements, they seem to work rather differently to python ones and they don't seem to be much use here.

it is nearly the same. Most fortran intrinsics operate component-wise on arrays ( assuming you have at least fortran95 )

 real a(2,4),b(4)
 a=reshape([.1,.2,.3,.4,.5,.6,.7,.8],shape(a)) 
 b=sum(min(1-a,a)**2,1)
 write(*,'(4f5.2)')b
 end

0.05 0.25 0.41 0.13

note fortran's sum would by default sum the whole array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM