Broadcast array multiplication in Fortran 90/95

2019-01-26 16:46发布

I was wondering that would there be a better (succinct) way to code this in Fortran? I am trying to multiply each column of a(3, 3) by each value in b(3). I know in Python there is np.multiply, and not sure about 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

Thanks in advance!

3条回答
叛逆
2楼-- · 2019-01-26 17:07

If you are reusing a particular b frequently you could define:

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

then you just can do:

 a=a*b

..

查看更多
神经病院院长
3楼-- · 2019-01-26 17:15

The do loop can be replaced by a one-liner using FORALL:

forall (i=1:3) a(:, i) = a(:, i) * b(i)
查看更多
Summer. ? 凉城
4楼-- · 2019-01-26 17:24

The expression

a * SPREAD(b,1,3)

will produce the same result as your loop. I'll leave it to you and to others to judge whether this is more succinct or in any way better than the loop.

查看更多
登录 后发表回答