Insert vector into matrix at specific columns

别等时光非礼了梦想. 提交于 2021-02-05 08:31:25

问题


How would I insert a vector b into a matrix at column col? I cannot find any syntax for and insert or append function in Fortran.

So far all I have done is reassigned the values in the column, but I only want to insert the vector.

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

回答1:


If I understood of your problem, you want to:

  • increase the number n of columns of the matrix m by 1;
  • insert the content of a vector b in m as a new column, at index col;
  • right-shift the remaining columns of m, in order to not lose any data.

Being this the case, you will need a couple of things:

  • matrix m must be allocatable if you want to update the data locally. If you want to return a new independent array as a result, this wouldn't be necessary (but an additional data copy would be made).
  • better use a compiler at least 2003 standard compliant so you have access to the intrinsic move_alloc, that avoid one array copy in the redimension.

Here is a demo implementation:

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

My output with gfortran 7.1.1 is:

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


来源:https://stackoverflow.com/questions/52571937/insert-vector-into-matrix-at-specific-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!