【问题标题】:Fortran logical indices from MatlabMatlab 中的 Fortran 逻辑索引
【发布时间】:2017-09-29 20:52:55
【问题描述】:

我正在尝试编写 Fortran 95 代码来模仿我在 MATLAB 中所做的事情,但我很难访问数组索引。代码比下面显示的要复杂得多,但这是要点。我宁愿避免做循环。

例如--> Matlab 命令。假设 a,b,c 大小相同。

    indx=find(a<0);  % find all negative values of "a"
    b(indx)=30.;  %  set those same elements in different array "b" to 30.
    c(indx)=b(indx)./a(indx)
    etc.
    etc.

如何存储和使用“a”数组中的这些索引,并在 fortran 中对其他数组中的相同索引进行操作?

【问题讨论】:

  • 它很接近,但它返回一个逻辑数组,它对于生成应用于其他数组的索引没有用处。
  • 您使用pack 和逻辑掩码为您提供充当向量下标的索引数组,或者使用带有掩码的where 语句/构造。

标签: matlab fortran


【解决方案1】:

你想要类似的东西

$ cat pack.f90
Program pack_test

  Implicit None

  Real, Dimension( 1:5 ) :: a
  Real, Dimension( 1: 5) :: b, c

  Integer, Dimension( : ), Allocatable :: indx

  Integer :: i

  a = [ 1, -2, 3, -4, 5 ]
  b = a
  c = a

  indx = Pack( [ ( i, i = Lbound( a, Dim = 1 )    , &
                          Ubound( a, Dim = 1 ) ) ], &
                a < 0 )

  b( indx ) = 30.0
  c( indx ) = b( indx ) / a( indx )

  Write( *, * ) c

End Program pack_test

ian-standard@barleybarber ~
$ gfortran -O -Wall -Wextra -fcheck=all -std=f2003 pack.f90

ian-standard@barleybarber ~
$ ./a.exe
   1.00000000      -15.0000000       3.00000000      -7.50000000       5.00000000

【讨论】:

    【解决方案2】:

    并不总是需要创建索引数组,如果不是,where 可能是正确的工具。例如,@IanBush 的答案中的代码可以这样修改:

    Program where_test
    
      Implicit None
    
      Real, Dimension( 1:5 ) :: a
      Real, Dimension( 1: 5) :: b, c
    
      Integer :: i
    
      a = [ 1, -2, 3, -4, 5 ]
      b = a
      c = a
    
      WHERE(a<0) b = 30.0
      WHERE(a<0) c = b/a
    
      Write( *, * ) c
    
    End Program where_test
    

    【讨论】:

    • 好点,在这种情况下这个更简单,应该想到了。我投票赞成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2016-08-28
    • 2014-11-05
    • 2023-03-10
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多