2013-11-05 85 views
2

存儲多維數組的Fortran 90的

module mymod 
contains 
    subroutine mysub(matrix_dum, i_size, j_size) 
    integer :: i, j, i_size, j_size 
    real(8), dimension(:,:) matrix_dum 
    do j=1, j_size 
     do i = 1, i_size 
     matrix_dum(i,j) = 11.d0*matrix_dum(i,j) 
     end do 
    end do 
    end subroutine mysub 
end module mymod 

program main 
    use mymod 
    implicit none 
    real(8), dimension(:,:,:), pointer :: matrix 
    integer :: i, num_matrices, i_size, j_size 
    num_matrices = 11 
    i_size = 5000 
    j_size = 6000 
    !only one of them are uncommented in actual practice 
    !I have two choices this choice takes a very very long time 
    allocate(matrix(num_matrices,i_size,j_size)) 
    matrix = 11.d0 
    do i = 1, num_matrices 
    call mysub(matrix(i,:,:),i_size,j_size) 
    end do 

    !this one does the same job instantly 
    allocate(matrix(i_size,j_size,num_matrices)) 
    matrix = 11.d0 
    do i = 1, num_matrices 
    call mysub(matrix(:,:,i),i_size,j_size) 
    end do 
    deallocate(matrix) 
end program main` 

爲什麼第二個工作如我所料,但先不。我知道這一定是Fortran將多維數組一個接一個地存儲在單一行中的方式。但我不確定我的語法。我是否正確地傳遞了矩陣的地址?還是我告訴它複製整個矩陣而不是給它地址。你如何將指針傳遞給多維數組的一部分?這裏發生了什麼?

回答

3

通常,Fortran處理器按照由語言定義的數組元素順序存儲數組 - 這樣,當您從元素移至元素時,最左側的下標變化最快。

所以矩陣(:,:,1)的所有元素都是連續的 - 彼此相鄰。

矩陣(1所述的元件,:,:)將不連續,如果SIZE(矩陣,1)/ = 1

上陣列

操作不在數組元素順序或者是不連續的通常較慢(例如,它們可能不太容易緩存,或者在某些情況下可能需要構建中間臨時陣列)。