Intrinsic matrix math

Sum and product

Sum and product reduce a whole array to one number. Add a mask to skip the elements you do not want. The mask must have the same shape as the array.

program sum_demo implicit none real :: a(4) = [1.0, 2.0, 3.0, 4.0] print *, sum(a) print *, product(a) print *, sum(a, mask = a > 0.0) end program sum_demo

Matmul

Matmul multiplies two matrices or a matrix with a vector. The inner sizes must agree: an (m, k) array times a (k, n) array gives an (m, n) array. Check shapes before the call to avoid a runtime error.

program mm_demo implicit none real :: a(2, 2) = reshape([1.0, 2.0, 3.0, 4.0], [2, 2]) real :: b(2, 2) = reshape([5.0, 6.0, 7.0, 8.0], [2, 2]) real :: c(2, 2) c = matmul(a, b) print *, c end program mm_demo

Transpose

Transpose flips rows and columns. The result of transposing a (2, 3) array is a (3, 2) array, so declare the target with swapped bounds.

program transpose_demo implicit none real :: a(2, 3) = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3]) real :: b(3, 2) b = transpose(a) print *, b end program transpose_demo

Reshape

Reshape packs flat data into any conformable shape. Shape reports the extents and size reports the element count. Use them together when a dummy argument accepts any shape.

program reshape_demo implicit none real :: v(6) = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] real :: m(2, 3) m = reshape(v, [2, 3]) print *, shape(m) print *, size(m) end program reshape_demo

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev