如何在Fortran代码中将2D数组转换为1D数组? [英] How to convert 2D array to 1D array in Fortran code?
问题描述
如何将r(i,j)转换为一维数组,以便可以轻松地对数字进行排序?
How do I convert r(i,j) to a 1D array so that I can sort the number easily?
program sort
implicit none
character CN*8,O*7
integer j,iconf,nconf
integer i,nbins,t
integer n,nmax,ind,num,b
parameter (n=216)
double precision xbox,rq
parameter (nmax=3091,nconf=1)
double precision atom(nmax),id(nmax),ox(nmax),oy(nmax),oz(nmax)
double precision xij,yij,zij,rij
double precision r(n,n),A(n)
open(unit=10,status='unknown',file='1000.gro')
do iconf= 1,nconf
write(*,*)iconf
read(10,*)
read(10,*)
do i=1,n
read(10,'(A8,A7,1i5,3f8.3)')CN,O,num,ox(i),oy(i),oz(i)
enddo
read(10,*)xbox ! read the xbox for PBC
open(unit=3,file='dist.txt')
do i=1,n
do j=1,n
if(i .ne. j) then
xij=ox(i)-ox(j)
yij=oy(i)-oy(j)
zij=oz(i)-oz(j)
r(i,j)=dsqrt(xij**2 + yij**2 + zij**2)
write(3,'(i3,2x,i3,4x,f17.15)') i,j, r(i,j)
endif
enddo
enddo
enddo
END
我必须计算距离并将其保存在数组中作为r (i,j)
.我想将r(i,j)
转换为一维数组,以便可以轻松地对r(i,j)
进行排序.
I have to calculate the distance and save this in array as r (i,j)
. I want to convert r(i,j)
to a 1 dimensional array, so that I can sort the r(i,j)
easily.
推荐答案
这似乎是为重塑功能量身定制的: https://gcc.gnu.org/onlinedocs/gfortran/RESHAPE.html 在这个小例子中,首先使用reshape制作二维数组A,然后再次调用reshape制作一维数组C.
This seems tailor made for the reshape function: https://gcc.gnu.org/onlinedocs/gfortran/RESHAPE.html In this tiny example, reshape is used first to make a two-dimensional array A, then reshape is called again to make the one-dimension array C.
Program reshape_demo
use, intrinsic :: iso_c_binding
implicit none
real(kind=c_float),allocatable :: A(:,:),C(:)
integer(kind=c_int) :: krow
allocate(A(3,3))
A=reshape((/1,2,3,4,5,6,7,8,9/),(/3,3/))
do krow=1,3
write(*,fmt="(1p3e10.3)")A(krow,:)
end do
C=reshape(A,(/9/))
write(*,fmt="(9(1x,f4.1))")C
End Program reshape_demo
这篇关于如何在Fortran代码中将2D数组转换为1D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!