program ArrayExample ! This file: ! http://ftp.aset.psu.edu/pub/ger/fortran/hdk/ArrayExample.f90 integer :: i integer, parameter:: n1=3, n2=4 real :: a, b dimension :: b(n1), a(n1,n2) a = 2.5; ! The means shoud all be 2.5. !Question from: Roland posted on comp.lang.fortran on 11 September 2006: !I have a 2-D array, a(n1, n2), and I want to compute the mean of each !row of the array and save the values in array b(n1). To accomplish this !task, I could write in Fortran 90 do i=1, n1 b(i)=sum(a(i, :))/n2 enddo print *, "b=",b !which needs three (3) lines of coding. !Now my question: Is there a way in Fortran 90 to put the above three !lines into just one (1) line? ! ! !Richard Maine's Reply: !See the DIM= argument to SUM. That's exactly the kind of thing it is !for. b = sum(a,dim=2)/n2 print *, "b=",b !Brooks Moses Reply: b = (/ (sum(a(i,:))/n2, i=1, n1) /) print *, "b=",b !or forall(i=1:n1) b(i)=sum(a(i,:))/n2 print *, "b=",b !Glen Hemannsfeldt and then Jaroslav Highegg Reply ! (more than one line, but perhaps more optimizable?): b = 0 do j=1,n2 b = b + a(:,j) end do b = b/n2 print *, "b=",b !Simon Geard Reply: ! !Isn't is faster to transpose the matrix and then sum over the columns? ! Richard Maine suggests not likely since implementation is compiler ! dependent. b = sum(transpose(a),dim=1)/n2 print *, "b=",b end program ArrayExample