Reputation: 153
When we deal with large arrays, it may be important to consider the cost of change of rank and shape of arrays specially when it happens a couple of times in multiple subroutines/functions.
The main purpose of my question is to change rank of arrays from 2nd to 1st and vice versa...
To do this one can use :
POINTER variables. Below is a code which shows how to utilize pointer variables:
program test
real, pointer :: a(:)
real, pointer :: b(:,:)
allocate(a(6))
a = (/1,2,3,4,5,6/)
b (1:2, 1:3) => a
WRITE(*,*) 'b=',b(3,1)
end program test
Questions : 1. Which method is faster? 2. Is there any other faster method? 3. Any other suggestion to do this work?
Thanks...
Upvotes: 6
Views: 2374
Reputation: 153
Well, Fortran is designed to be the language of MATH. I dug a little bit and I came across the below points in Fortran.
Some explanation before explaining the points :
My subroutine must work with 1st rank arrays. I am calling 2nd rank arrays as input at the beginning of the subroutine. Then, I need to change the rank from 2nd to 1st. Later in the subroutine, I need to change the rank back to 2. This changing of ranks is happening 3-4 times in the code.
This is the fastest method. Nothing changes in the memory and I thought it is the best. However, it ends with attribute conflict errors for my problem, because I am working inside a subroutine.
I have tried pointer then. But, it seems that it is not possible to remap a 2nd rank array into a 1st rank array. Remapping 1st rank to 2nd rank arrays works fine.
The simple code, I wrote to remap a 1st rank array into a 2nd rank array :
program ptrtest
real, pointer :: a(:)
real, pointer :: b(:,:)
allocate(b(1:2,1:3))
b = transpose(reshape((/ 1, 2, 3, 4, 5, 6 /), shape(b)))
a(1:6) => b(:,:)
WRITE(*,*) a(4), b(2,2) ! to see if the remapped elements are same?
end program ptrtest
The error that I have received :
gfortran -Wall -o "POINTER" "POINTER.f90" (in directory: /home/vahid/Desktop)
POINTER.f90:12.14:
a(1:6) => b(:,:)
1
Error: Rank remapping target must be rank 1 or simply contiguous at (1)
Compilation failed.
The slowest method which is able to do any type of transition. Basically, it assigns another memory locations for the transitioned element which is expensive, considering both memory efficiency and processing costs.
As a consequence, Fortran 2003 manual states that: (section 2.2.4 and 5.2)
Data objects may be dynamic in size, shape, type, or length type parameters, but not rank or kind type parameters.
I don't know the consequences, but I think the rank of arrays should be dynamic also. Please correct if any part is wrong.
Upvotes: 4