【问题标题】:Is there a way to associate an array slice indices in Fortran?有没有办法在 Fortran 中关联数组切片索引?
【发布时间】:2019-05-03 19:16:31
【问题描述】:

我正在实现一个将矩阵乘以向量的函数。

矩阵以 CSR(压缩稀疏行)格式存储:

type csr_matrix ! Compressed Sparse Row
    integer, dimension(:), allocatable :: row_offsets ! dimension(nrows + 1)
    integer, dimension(:), allocatable :: columns ! dimension(nnz)
    real(dp), dimension(:), allocatable :: values ! dimension(nnz)
end type

以下代码成功编译并正常工作:

res = 0
do i = 1, size(b)
    associate( &
        lbound => A%row_offsets(i) + 1, &
        ubound => A%row_offsets(i + 1) &
        )
        res(i) = res(i) + dot_product(A%values(lbound:ubound), b(A%columns(lbound:ubound)))
    end associate
end do

lbound:ubound 表达式出现了两次,所以我认为通过将 lboundubound 的关联替换为单个 slice_ind 关联来重构代码会很好:

res = 0
do i = 1, size(b)
    associate(slice_ind => A%row_offsets(i) + 1 : A%row_offsets(i + 1))
        res(i) = res(i) + dot_product(A%values(slice_ind), b(A%columns(slice_ind)))
    end associate
end do

但是编译器会产生错误:

error #5082: Syntax error, found ':' when expecting one of: ) ,

有没有办法在 fortran 中进行这种关联?如果没有,有没有更好的方法让代码更具可读性?

【问题讨论】:

    标签: fortran


    【解决方案1】:

    不,不可能,代码无效。您只能在创建子数组(数组部分)时使用:,或者在某些声明和分配中使用::

    您必须使用带有标量 lboundubound 的版本。通常,无法将数组索引表达式(单个或多个维度)存储在变量或数组中。一个例外是一维向量索引,其中数组包含所有索引。

    【讨论】:

    • 感谢您的回答。我想我可以显式地创建一个一维向量索引数组,但这将是一种低效的方法。
    • 效率很低。
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2019-03-18
    • 1970-01-01
    • 2014-06-28
    • 2022-11-17
    • 2021-08-11
    相关资源
    最近更新 更多