Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcast array multiplication in Fortran 90/95

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!

like image 620
Yuxiang Wang Avatar asked Jan 15 '15 17:01

Yuxiang Wang


People also ask

How are arrays defined and used in Fortran 90?

Arrays are declared with the dimension attribute. The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).

How do I add an array in Fortran?

In Fortran 90, it is as simple as C = A + B . Note: C = A*B multplies corresponding elements in A and B.

What is reshape Fortran?

reshape(source, shape, pad, order) It constructs an array with a specified shape shape starting from the elements in a given array source. If pad is not included then the size of source has to be at least product (shape). If pad is included, it has to have the same type as source.

What is dimension in Fortran?

The DIMENSION statement specifies the number of dimensions for an array, including the number of elements in each dimension. Optionally, the DIMENSION statement initializes items with values.


2 Answers

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.

like image 160
High Performance Mark Avatar answered Oct 31 '22 04:10

High Performance Mark


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

forall (i=1:3) a(:, i) = a(:, i) * b(i)
like image 33
Fortranner Avatar answered Oct 31 '22 03:10

Fortranner