矩阵和向量的Fortran元素明智乘法 [英] Fortran element wise multiplication of a matrix and a vector

查看:99
本文介绍了矩阵和向量的Fortran元素明智乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单快捷的方法可以将矩阵的一列与向量的元素相乘.我们可以明确地做到这一点,

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

是否有一种方法可以在一行中执行do循环.例如,在Numpy python中,我们可以一次完成这项工作

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]

推荐答案

尝试

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

,如果那行不通(这台计算机上没有Fortran,所以我没有检查过),则摆弄 spread ,直到它生效为止.实际上,您可能希望将 3 替换为 size(x,1)等.

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.

我希望这会导致编译器创建临时数组.而且我希望能够轻松找到在问题中表现不佳的显式循环方案的情况.纯净的"单线通常在时间和空间上都有成本.经常使用的经过验证的Fortran显式循环方法是一种.

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.

这篇关于矩阵和向量的Fortran元素明智乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆