Reputation: 139
I have the following line to delcare a higher-dimensional array in Fortran:
real(8) X(48,20,7,3), Y(48,15,5)
My question is how do we interpret an n-dimensional array? I want to know the meaning of the subscripts. Also, if it is at all possible, I would appreciate if you can provide the equivalent code to create the same 4D and 3D arrays in Matlab.
I have tried looking around for this interpretation, but have only found examples mentioning that it is possible to do it without an explanation as to the meaning of the subscripts. I would appreciate very much your help.
Upvotes: 0
Views: 147
Reputation: 60058
An array is a collection of array elements (e.g., numbers like real
or integer
or some other type) that are stored in a defined order and by-default contiguously in memory.
That means that for a 1D array the second element comes after the first one, then comes the third one...
For multi-D arrays you store them in Fortran in a so called column-major order. It is the same order as the one used in MATLAB. The means that you store the elements in an order in which the elements that have the same last index are stored contiguously in memory.
In 2D: A(2,3), the order is: A(1,1), A(2,1), A(1,2), A(2,2), A(3,1), A(3,2)
Comparing to MATLAB. Lets take this array
a = [1 3; 2 4; 7 8]
The matrix looks like
1 3
2 4
7 8
In Matlab you use the rows in the constructor, even-though MATLAB stores the array with contiguous columns. This may be confusing.
in Fortran this is a(3,2)
and can be constructed as
a = reshape([1, 2, 7, 3, 4, 8], [3,2])
The numbers are stored in this order: 1, 2, 7, 3, 4, 8 in both languages.
In both languages the array element a(2,1)
is equal to 2.
3D and 4D arrays extend this naturally, but are less convenient for simple examples in an answer.
If you have a 3D array B(n1, n2, n3)
then the order of the element B(i1, i2, i3)
in the linear order in memory is (i3-1)*n2 + (i2-1)*n1 + i1
(assuming the first element is element number 1).
Upvotes: 5