Fortran 90/95 中的广播数组乘法

Broadcast array multiplication in Fortran 90/95

我想知道是否有更好(简洁)的方法用 Fortran 对此进行编码?我正在尝试将 a(3, 3) 的每一列乘以 b(3) 中的每个值。我知道 Python 中有 np.multiply,但不确定 Fortran。

!!! test.f90
program test
    implicit none
    integer, parameter :: dp=kind(0.d0)
    real(dp) :: a(3, 3)=reshape([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]),&
        b(3)=[1, 2, 3]
    integer :: i
    do i = 1, 3
        a(:, i) = a(:, i) * b(i)
    end do
    write(*, *) a
end program test

提前致谢!

如果您经常重复使用特定的 b,您可以定义:

 b(3, 3)=reshape([1, 1, 1, 2, 2, 2, 3, 3, 3], [3, 3])

那么你可以这样做:

 a=a*b

..

表达式

a * SPREAD(b,1,3)

将产生与您的循环相同的结果。我会留给你和其他人来判断这是否比循环更简洁或更好。

可以使用 FORALL 将 do 循环替换为单行代码:

forall (i=1:3) a(:, i) = a(:, i) * b(i)