如何为矩阵的对角线分配一个指针? [英] How to assign a pointer to a diagonal of a matrix?

查看:122
本文介绍了如何为矩阵的对角线分配一个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵,例如REAL*8 MATRIX(100,100),我想从主对角线或上三角创建一个指针.该怎么做?

I have a matrix say REAL*8 MATRIX(100,100), I want to create a pointer out of just the main diagonal or the upper triangle. How to do that?

目的是以干净的命名"方式轻松访问这些元素.

The purpose is to easily access those elements in a clean "named" way.

推荐答案

对于主对角线,可以小心地进行以下操作:

For the main diagonal, with care, you can do something like:

PROGRAM diagonal
  IMPLICIT NONE
  REAL, TARGET :: array(4,4)
  REAL, POINTER :: ptr(:)
  INTEGER :: i
  array = RESHAPE([(i,i=1,SIZE(array))], SHAPE(array))
  CALL get_diagonal_pointer(array, SIZE(array, 1), ptr)
  PRINT "(*(G0,:,','))", ptr
CONTAINS
  SUBROUTINE get_diagonal_pointer(arr, n, ptr)
    REAL, INTENT(IN), TARGET :: arr(*)
    INTEGER, INTENT(IN) :: n
    REAL, INTENT(OUT), POINTER :: ptr(:)
    !****
    ptr => arr(1:n*n:n+1)
  END SUBROUTINE get_diagonal_pointer
END PROGRAM diagonal

但是请注意,主程序中的array连续的,并具有TARGET属性.如果array不只是连续的,那么事情就会变得很复杂.

But note that array in the main program is simply contiguous and has the TARGET attribute. If array was not simply contiguous, then things get ... complicated.

您可以使用中间等级为1的指针和指针边界重新映射来完成相同操作.适用与假定大小法相同的要求.

You can accomplish the same using an intermediate rank one pointer and pointer bounds remapping. The same requirements as for the assumed size approach apply.

REAL, POINTER :: tmp(:)
tmp(1:SIZE(array)) => array
ptr => tmp(::SIZE(array,1)+1)

矩阵的上三角不是正则"的(要指向的元素之间的间距是变化的),因此不能指向它.

The upper triangle of a matrix is not "regular" (the spacing between elements that you want to point at varies) and hence it can't be pointed at.

这篇关于如何为矩阵的对角线分配一个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆