alohomora100 发表于 2017-7-7 14:37:06

Fortran如何实现1000个变量循环赋10个值

目下,我有1000个变量,想循环赋10个值,也就是说变量1-10赋值1-10,变量11-20还是赋值1-10,不知道该如何实现,望大家帮助下,多谢

vvt 发表于 2017-7-7 15:10:14

本帖最后由 vvt 于 2017-7-7 15:16 编辑

real :: a(1000)
integer :: i
Do i = 1 , 10
    a(i::10) = i
End Do

a( x : y : z ) = i 的意思是,从第x个开始,到第y个结束,每z个数赋值为 i
(其中x忽略则从数据最开始开始,y忽略则到数组最尾端结束,z忽略则每1个数赋值)

所以 a( i : : 10 ) = i 的意思是,从第 i 个,到最后一个,每10个数赋值为i


alohomora100 发表于 2017-7-7 15:18:47

vvt 发表于 2017-7-7 15:10
real :: a(1000)
integer :: i
Do i = 1 , 10


多谢多谢,刚学写程序好多都不太会。

百事可乐 发表于 2017-7-7 15:27:43

还有更简便的写法
a = reshape(spread(,2,100),shape(a))
它把 [ 1:10 ] 在第 2 个维度上延伸 100 倍。变成 10*100 的二维数组。然后再 reshape 成 a 的外形(即 1000 的一维数组)

alohomora100 发表于 2017-7-7 15:49:31

vvt 发表于 2017-7-7 15:10
real :: a(1000)
integer :: i
Do i = 1 , 10

我是想这么赋值的,不知道行不行?多谢      
program aweigh
          implicit real*8 (a-h,o-z)
          dimension wa(10000,1)
          real::a(10000)
          parameter(N=14.00672)
          parameter(H=1.00795)
          parameter(C=12.01078)
          open(13,file='aweigh.txt')
          do i=1,10
            if ((i.eq.1).or.(i.eq.5))
                then a(i::10)=N
                endif
                if ((i.eq.3).or.(i.eq.4).or.(i.eq.8))
                then a(i::10)=C
                else a(i::10)=H
                endif
      enddo               
          do i=1,10000
          write(3,*)a(i)
          enddo
          close(13)
          end

alohomora100 发表于 2017-7-7 16:15:17

百事可乐 发表于 2017-7-7 15:27
还有更简便的写法

...

多谢多谢

vvt 发表于 2017-7-7 16:31:26

program aweigh
implicit none !//这句话非常非常重要!!请一定要写 implicit none
real(8) :: a(10000)
integer :: i
Real(8) , parameter :: N=14.00672 !// N 要定义成 real8
Real(8) , parameter :: H=1.00795
Real(8) , parameter :: C=12.01078
open(13,file='aweigh.txt')
do i=1,10
    Select Case( i ) !//用 Select 语句,方便直观
    Case(1,5)
      a(i::10)=N
    Case(3,4,8)
      a(i::10)=C
    Case Default
      a(i::10)=H
    End Select
enddo
do i=1,10000
    write(3,*)a(i)
enddo
close(13)
end program aweigh

alohomora100 发表于 2017-7-7 16:42:00

vvt 发表于 2017-7-7 16:31
program aweigh
implicit none !//这句话非常非常重要!!请一定要写 implici ...

多谢多谢

维尼猴 发表于 2017-7-16 09:56:15

学习了,很不错

chiangtp 发表于 2017-8-12 19:36:05

1. 樓主有興趣"學習語法"的話, 可進一步把vvt(7#)範例, 用FORALL改寫
2. 請樓主沒事別用"double precision", 突顯自己的無知而已

PROGRAM test
IMPLICIT NONE
! "(8)" compiler dependent (NAG/Silverfrost not accept), avoid to use
REAL(8) , PARAMETER :: N=14.00672
REAL(8) , PARAMETER :: H= 1.00795
REAL(8) , PARAMETER :: C=12.01078

INTEGER, PARAMETER :: r8=SELECTED_REAL_KIND(P=15)
REAL(r8) , PARAMETER :: NN=14.00672_r8
REAL(r8) , PARAMETER :: HH= 1.00795_r8
REAL(r8) , PARAMETER :: CC=12.01078_r8

WRITE(*,*) N, NN
WRITE(*,*) H, HH
WRITE(*,*) C, CC
END PROGRAM test

3. 蒐集到的資料, 請參考:
页: [1]
查看完整版本: Fortran如何实现1000个变量循环赋10个值