Fortran 中没有基本操作可以根据排除标准选择数组的特定元素集。但是,有几种方法可用,但工作量更大。
如果可以构造一个包含所需索引的数组,则可以使用向量下标
integer a(10)
integer, allocatable :: idx(:)
idx = [...] ! An array constructor of the desired elements to select
a(idx) = 2*a(idx)
对于问题的情况,这样的数组构造函数很可能是idx=[1,(i,i=3,10)]。我们可以在很多语句中建立这个数组,甚至不用变量作为向量下标。
我们可以使用 WHERE 构造来选择要作用于数组的元素
integer a(10), i
a = 1
where ([(i,i=1,10)]/=2) ! Or other selecting expression
a = 2*a
end where
(对于标记为 Fortran 90,请改用数组构造函数 (/(...)/)。)
还有一些围绕数组部分的方法(如 Tine198 的回答),或者只是在循环中使用排除:
do i=1, 10
if (i==2) cycle ! Or other element exclusion criterion
a(i) = 2*a(i)
end do