Say I have a 3D array, A(1:3,1:4,1:5), and I only want to deal with part of it, e.g.:
real :: A(1:3,1:4,1:5), B(1:5,1:2)
real, allocatable :: C(:,:)
allocate(C(size(A,1),size(B,2)))
C = matmul(A(1:3,1,1:5),B)
Fortran seems fine with that. However, if I needed to deal with the transpose, then the transpose function in Fortran gets confused, e.g.:
real :: A(1:3,1:4,1:5), B(1:3,1:2)
real, allocatable :: C(:,:)
allocate(C(size(A,3),size(B,2)))
C = matmul(transpose(A(1:3,1,1:5)),B)
How can I swap dimensions around in an array with Fortran? For example, I have A(3,4,5); is there a function/command that takes this and gives me A(5,4,3) or A(4,3,5) or any arrangement I could wish for? Without, of course, doing something like copying A to a dummy array with the dimensions in the order required. I’m looking for a simple one line elegant way.
Thank you.
You don’t have a problem with
TRANSPOSE. It is working just fine for the sample code you provided. The problem is that your arrays are not compatible for matrix multiplication. From Fortran 2008 Standard draft:In your case:
Here,
transpose(A(1:3,1,1:5))is a 5×3 matrix, and B is 2×5. Thus, these two matrices are non-comformable forMATMUL. I am wondering how you did not catch on this since compilers give a clear error message:gfortran 4.1.2:
ifort 12.0.2.137:
pgf90 10.6-0 compiles but produces a run-time error:
For reshaping arrays in Fortran, you can use intrinsic function
RESHAPE. From Fortran 2008 Standard draft: