Fortran
Arrays and Vector Operations
Create and operate on arrays in modern Fortran.
By EZ4Code Team
arrayvector
Code
program arrays
implicit none
! 1D array
real, dimension(10) :: a
real :: b(5) = [1.0, 2.0, 3.0, 4.0, 5.0]
! 2D array
real :: m(3, 4)
! Array constructor
a = [(real(i), i=1, 10)] ! 1.0, 2.0, ..., 10.0
! Whole-array operations (vectorized)
a = a * 2.0
a = a + b ! must conform (here both size 10... adjust)
! Intrinsic functions
print *, sum(b) ! 15.0
print *, maxval(b) ! 5.0
print *, size(b) ! 5
print *, sum(b, mask=b>2) ! 12.0
! Array sections
print *, b(2:4) ! [2.0, 3.0, 4.0]
print *, b(::2) ! [1.0, 3.0, 5.0] (stride 2)
end programExplanation
Fortran arrays are 1-indexed by default. Use array constructors [..] to initialize. Whole-array operations are vectorized — no explicit loops needed, and often faster. Array sections (start:end:stride) extract slices. Intrinsics like sum, maxval, minval accept masks for conditional aggregation.
More Fortran Snippets
Subroutines and Functions
Define reusable procedures in Fortran.
Modules and Derived Types
Organize code with modules and OOP-style types.
File I/O and Formatting
Read/write files with formatted output.
OpenMP Parallelism
Parallelize loops with OpenMP directives.
Numerical: Linear Algebra (BLAS/LAPACK)
Call BLAS/LAPACK for matrix operations.
Derived Types and Pointers
Custom types with allocatable components and pointers.