Fortran element wise multiplication of a matrix and a vector

﹥>﹥吖頭↗ 提交于 2021-02-07 21:02:11

问题


Is there a simple and quick way to multiply a column of a matrix with element of a vector. We can do this explicitly,

program test
   integer :: x(3,3), y(3), z(3,3)
   x = reshape([(i,i=1,9)],[3,3])
   y = [1,2,3]
   do i=1,3
      z(:,i) = x(:,i) * y(i)
      print *, z(:,i)
   enddo
end program test

Is there a way to perform the do loop in one line. For example in Numpy python we can do this to do the job in one shot

z = np.einsum('ij,i->ij',x,y)
#or
z = x*y[:,None]

回答1:


Try

z = x * spread(y,1,3)

and if that doesn't work (no Fortran on this computer so I haven't checked) fiddle around with spread until it does. In practice you'll probably want to replace the 3 by size(x,1) or suchlike.

I expect that this will cause the compiler to create temporary arrays. And I expect it will be easy to find situations where it underperforms the explicit looping scheme in the question. 'neat' one-liners often have a cost in both time and space. And often tried-and-trusted Fortran approach of explicit looping is the one to go with.




回答2:


Why replace clear easy to read code with garbage?

program test
  implicit none
  integer i,j
  integer :: x(3,3), y(3), z(3,3)
  x = reshape([(i,i=1,9)],[3,3])
  y = [1,2,3]
  z = reshape ([((x(j,i)*y(i) ,j=1,3),i=1,3)], [3,3])
  print *, z(1,:)
  print *, z(2,:)
  print *, z(3,:)
end program test


来源:https://stackoverflow.com/questions/59269264/fortran-element-wise-multiplication-of-a-matrix-and-a-vector

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