我有一个包含40个值的列矩阵。说,
1
4
5
2
4
1
9
.
.
.
2
如何调用每四个值并将它们平均直到达到40?我设法以下面的方式做,但有更好的方法吗?贝斯特!
i = 1, 4
avg1 = avg + avg(i)
i = 5,8
avg2 = avg + avg(i)
i = 9,12
avg3 = avg + avg(i)
.......
i = 37,40
avg10 = avg + avg(i)
答案 0 :(得分:2)
我花了几次迭代才能使语法正确,但是这个怎么样?
integer, parameter, dimension(*) :: a = [ 1, 4, 5, ..., 2 ] integer :: i real, dimension(10) :: avg avg = [ (sum(a(i * 4 + 1 : (i + 1) * 4)) / 4., i = 0, 9) ] print *, avg end
答案 1 :(得分:0)
那怎么样?
program testing
implicit none
integer, dimension(40) :: array
real, dimension(10) :: averages
integer :: i, j, k, aux
array(:) = (/(i, i=1,40)/) ! just values 1 to 40
averages(:) = 0.0
k = 1 ! to keep track of where to store the next average
do i=1,40,4 ! iterate over the entire array in steps of 4
aux = 0 ! just a little helper variable, not really required, but neater I think
do j=i,i+3 ! iterating over 4 consecutive values
aux = aux + array(j)
end do
averages(k) = aux / 4.0
k = k + 1
end do
print *, averages
end program testing
这是输出:
2.500000 6.500000 10.50000 14.50000 18.50000
22.50000 26.50000 30.50000 34.50000 38.50000
这是你在找什么?