5

Is there a way to set an array (vector, or matrix, or even a scalar) to zero yet in Fortran? 2003/2008 seem to be taking Fortran to a very modern level, and I have to wonder if they have included an easy way to set array values to zero without having to do

do i = 1,X

        do j = 1,Y

            A(i,j) = 0

        enddo

enddo

Where X is the number of rows and Y is the number of columns in a 2-d matrix. This could be generalized to as many dimensions as you like, but the principle is the same.

In Matlab this is easily done with the zeros function, i.e.,

A = zeros(X,Y)

Modern Fortran seems to be incorporating a lot of the things people like about Matlab and other languages into it's repertoire, so I am just curious if they have an intrinsic for this simple and basic task yet.

Or maybe in modern Fortran it isn't necessary to clear out any previously stored values in the memory by initializing arrays?

I guess a shorter way would be to just go

real, dimension(X,Y)        :: A

A = A*0.0 ! Set all elements to zero by multiplying matrix by scalar value 0

But the question about an intrinsic still stands.

Charlie Crown
  • 1,071
  • 2
  • 11
  • 28
  • 6
    I think `A = 0.0` will do it. – rici Apr 16 '17 at 02:15
  • @rici, you are correct. That is a very simple solution to something I have been doing overkill. – Charlie Crown Apr 16 '17 at 05:15
  • 2
    You've found the right answer, but please note your "multiply by zero" method is not correct - it is never correct to use an uninitialised variable in an expression – Ian Bush Apr 16 '17 at 06:07
  • Also, it can be ensured via compiler options. The [-finit-local-zero](https://gcc.gnu.org/onlinedocs/gfortran/Code-Gen-Options.html) option instructs the compiler to initialize local INTEGER, REAL, and COMPLEX variables to zero for gfortran. – trblnc Apr 17 '17 at 08:28
  • 2
    Please don't do this, an assumption like that makes your code non-standard conforming – Ian Bush Apr 18 '17 at 09:39
  • 1
    Yeap, my previous comment clearly advice a bad practice, it exist, but not recommended to use, see [also](https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/597810). I wonder if there is any other good enough reason to use that option apart from debugging. – trblnc Apr 18 '17 at 13:01

1 Answers1

14

It turns out the answer is quite simple.

A = 0.0 

or just

A = 0

will set all elements in your array to 0.0000...

(Moved from the question.)