using fortran derived type variable without %

374 Views Asked by At

I define a type named MATRIX and a variable of this type named A as the following

TYPE MATRIX
    REAL, ALLOCATABLE, DIMENSION(:,:) :: MAT
END TYPE

TYPE(MATRIX) :: A

the usual way of constructing A and then using it is

ALLOCATE(A%MAT(2,2))

A%MAT(1,:) = [1,2]
A%MAT(2,:) = [3,4]

PRINT*, A%MAT

I'd like to know that if it's possible to work with variable A without having to write A%MAT. In other words, is there any workaround to rewrite the former block of code in the following form (using A instead of A%MAT)

ALLOCATE(A(2,2))

A(1,:) = [1,2]
A(2,:) = [3,4]

PRINT*, A
2

There are 2 best solutions below

0
veryreverie On BEST ANSWER

Unfortunately, the syntax a(1,:) = [1,2] where a is a derived type is not currently allowed by the Fortran standard (Fortran 2018 at the time of writing).

There is a proposal to allow this in a future Fortran standard.

2
mcocdawc On

You can use the associate statement to bind certain expressions to a shorter name. This can be used to give a name to a component of a variable.

    allocate(A%mat(2, 2))
    associate(B => A%mat(:, :))
        B(1,:) = [1, 2]
        B(2,:) = [3, 4]
        write(*, *) B
    end associate

Note that you can also use reshape and automatic allocation to get rid of some slices.

! No allocate statement necessary.
A%mat = reshape([1, 2, 3, 4], [2, 2])