如何访问Fortran中数组中的最后一项?

19 arrays indexing fortran

在Matlab中,end索引允许我访问最后一项.

> array = [1 2 3 4 5 6 7];
> array(end)
ans =  7
Run Code Online (Sandbox Code Playgroud)

我如何在Fortran中做同样的事情?

program hello
   integer array(7)
   array = (/1, 2, 3, 4, 5, 6, 7/)
!print *, array(end)
!               1
!Error: Legacy Extension: REAL array index at (1)

! print *, array(-1)
!                1
!Warning: Array reference at (1) is out of bounds (-1 < 1) in dimension 1

! print *, array(0)
!                1
!Warning: Array reference at (1) is out of bounds (0 < 1) in dimension 1
end program Hello
Run Code Online (Sandbox Code Playgroud)

M. *_* B. 19

array ( ubound (array) )
Run Code Online (Sandbox Code Playgroud)

size 仅在数组为1索引时才有效.

  • 注意:如果你有一个多维数组,你需要指定`array(ubound(array,dim = n))`其中`n`是你要查找的维度. (9认同)

age*_*ntp 7

没有这样的方便符号,你需要这样做

 array(size(array))
Run Code Online (Sandbox Code Playgroud)

在较旧的fortran版本中,你甚至没有 size()并且需要自己跟踪尺寸

值得注意的是,fortran数组可以被定义为具有负索引,因此在其他一些语言中使用的结束符号将是不明确的