Brooks (brooksmoses) wrote,
Brooks
brooksmoses

Why I like Fortran (reason # 324)

Consider the following simplified piece of a program that I was recently writing:
type vector
  real :: x, y, z
end type

type field
  type(vector) :: data(5,5,5)
end type

type(field) my_field

my_field%data(:,:,2)%z = 3
Most of that's just setup of user-defined variable types, and is nothing different than one would do in C++. It sets up a type called vector with real-number variables x, y, and z; sets up a field type containing a component data, which is a three-dimensional array of vectors (I've used fixed values for the dimensions to make things simple); and defines a variable my_field of this type. Also, Fortran has a slightly different notation for accessing components; one writes my_field%data rather than the my_field.data that most other languages use.

The part that's particularly nice about Fortran is the last line, which illustrates what I can do with this -- and, in particular, how array indexing works in combination with data structures of this sort. The index notation (:,:,2) represents the portion of the array where the first two indices can take on any value, but the third index is limited to 2 -- that is, a two-dimensional slice through the overall array. Thus, my_field%data(:,:,2)%z is exactly what it looks like -- a reference to all of the z components of the vectors that make up that slice. Fortran treats this as equivalent to any other two-dimensional array; in this case, I've assigned it to a constant value of 3, which simply sets the z components of all the elements in the slice to 3. That's a rather trivial example; there are far more interesting ones, like passing it as an argument to a function that expects a two-dimensional array of real numbers.
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 4 comments