Fortran中的随机数组/矩阵初始化

时间:2014-03-25 13:47:13

标签: random matrix fortran fortran95

有没有办法在不使用显式do循环的情况下初始化随机数组?

现在我的随机矩阵初始化看起来像

program Main
    implicit none
    save

    integer :: seed, i, j
    real :: x
    character(100) :: option
    real, dimension(10,10) :: matrix

    if (iargc() > 0) then
        CALL GETARG(1,option)
        read(option,*) seed
    else
        seed = 1
    end if 

    call RANDOM_SEED(seed)

    do i=1,10
        do j=1,10
            call RANDOM_NUMBER(x)
            matrix(i,j) = x
        end do
    end do
end program

但是如果可能的话,我希望它更像是隐含的do-loop数组初始化:

program Main
    implicit none
    save

    integer :: seed
    character(100) :: option
    real, dimension(10,10) :: matrix

    if (iargc() > 0) then
        CALL GETARG(1,option)
        read(option,*) seed
    else
        seed = 5
    end if 

    call RANDOM_SEED(seed)

    matrix = reshape((/ ((call RANDOM_NUMBER()), i=1,100) /), shape(matrix))
end program

使用Fortran 95有什么办法可以做到这一点吗?

1 个答案:

答案 0 :(得分:14)

为什么不

call RANDOM_NUMBER(matrix)