将向量插入特定列的矩阵

Insert vector into matrix at specific columns

如何将向量 b 插入矩阵的 col 列?我在 Fortran 中找不到任何语法和插入或追加函数。

到目前为止,我所做的只是重新分配列中的值,但我只想插入向量。

real :: M(n,n)
integer :: n, col 
real :: b(n)
M(n:col) = b(:)

如果我理解你的问题,你想:

  • 将矩阵 m 的列数 n 增加 1;
  • 将向量 b 的内容作为新列插入 m 中,索引为 col
  • 右移 m 的剩余列,以免丢失任何数据。

在这种情况下,您需要做一些事情:

    如果要在本地更新数据,
  • 矩阵m 必须是allocatable。如果你想return一个新的独立数组作为结果,这不是必需的(但会制作一个额外的数据副本)。
  • 最好使用至少符合 2003 标准的编译器,这样您就可以访问内在的 move_alloc,避免在重新维度中复制一个数组。

这是一个演示实现:

program insert_vec
  integer, allocatable :: m(:, :), b(:)
  integer :: n = 3, col = 2, i
  allocate(m(n, n))
  allocate(b(n))
  m = 10
  b = [(i, i = 1, n)]
  call insert(m, b, col)
  do i = 1, n
      print *, m(i, :)
  end do
contains
  subroutine insert(m, b, col)
    integer, allocatable, intent(inout) :: m(:, :)
    integer, intent(in) :: b(size(m, 1)), col
    integer, allocatable :: temp(:, :)
    integer :: rows, cols
    rows = size(m, 1)
    cols = size(m, 2)
    allocate(temp(rows, cols + 1))
    temp(:, 1:col) = m(:, 1:col)
    temp(:, col) = b
    temp(:, col + 1:cols + 1) = m(:, col:cols)
    call move_alloc(temp, m)
  end
end

我的 gfortran 7.1.1 输出是:

      10           1          10          10
      10           2          10          10
      10           3          10          10