【问题标题】:Insert vector into matrix at specific columns将向量插入到特定列的矩阵中
【发布时间】:2018-09-29 19:44:11
【问题描述】:

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

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

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

【问题讨论】:

  • 所以当我理解正确时,您希望将向量 b 插入到矩阵 M 中,其中 M 的大小为 nxnb 的大小为 n。假设 n M(:,col) = b 或 M(1:n,col) = b(1:n)
  • @albert,我猜 OP 正试图将矩阵 M 的一维增加一然后在索引 col 的列中插入向量 b,从索引 col 中右移所有列,..,n到 col+1,...,n+1,为 b 腾出空间。对吗?
  • @RodrigoRodrigues 可能是这种情况,但我从这个问题中并不是 100% 清楚。在这种情况下,我们需要知道 OP 如何声明 M 矩阵,请 OP 提供详细信息,阅读 Minimal, Complete, and Verifiable example 并提供一个。

标签: matrix fortran gfortran


【解决方案1】:

如果我了解您的问题,您希望:

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

既然如此,您将需要几件事:

  • 如果要在本地更新数据,矩阵m 必须为allocatable。如果您想返回一个新的独立数组作为结果,这不是必需的(但会制作额外的数据副本)。
  • 最好使用至少符合 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多