Hello. I have two matrices A and B that I am taking through a loop and each iteration I would like to swap their places (like how you solve Laplace’s equation by relaxation).
Now I know you could have an even and odd loop (which is what I did before, but now I am changing that part of my code) and essentially duplicate code (or write a function and call it changing up matrix arguments), but for what I am doing I do not want to do that.
My arrays happen to be allocatable so I came up with two solutions (besides plain copying): make them pointers (or targets) and interchange what they point at, or use move_alloc in basically the same way. Here is an example of each (obviously not inside the loop I am talking about):
program main
use iso_fortran_env, only: dp => real64
implicit none
integer, parameter :: m = 4
real(dp), pointer :: A(:, :), B(:, :), temp(:, :)
allocate(A(m, m), B(m, m))
call random_number(A)
! A has random numbers I want to refer to by the name B,
! and I want to use the name A again for something else
temp => A
A => B
B => temp
! Now B has the random numbers A had,
! and I can use A for something else.
deallocate(A, B)
endprogram main
program main
use iso_fortran_env, only: dp => real64
implicit none
integer, parameter :: m = 4
real(dp), allocatable :: A(:, :), B(:, :), temp(:, :)
allocate(A(m, m), B(m, m))
call random_number(A)
! A has random numbers I want to refer to by the name B,
! and I want to use the name A again for something else
call move_alloc(A, temp)
call move_alloc(B, A)
call move_alloc(temp, B)
! Now B has the random numbers A had,
! and I can use A for something else.
deallocate(A, B)
endprogram main
Ideally I would like to not use pointers since they are a pain in Fortran and I have heard they can be quite bad on performance especially in Fortran. move_alloc is a thing I have only ever used once or twice before in the language for minor tasks, so I am uncertain about its performance impact (it could so happen it secretly will just keep allocating and deallocating in my code and be even worse than plain copying).
Anyways, I thought this sort of thing would be a somewhat common issue so there would be a “figured out” solution in the language but I haven’t been able to find one. If anyone has a good solution (or that one doesn’t exist, so I would have to suck it up and do the loop alternating thing) for this I would appreciate it (now that I type this I think clever use of associate might be another possible solution, but I’ll have to try it out).