将向量插入矩阵的特定列 [英] Insert vector into matrix at specific columns
本文介绍了将向量插入矩阵的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将向量b插入列col的矩阵中?我在Fortran中找不到任何语法以及插入或追加函数.
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(:)
推荐答案
如果我了解您的问题,则希望:
If I understood of your problem, you want to:
- 将矩阵
m
的列数n
增加1; - 将向量
b
的内容作为新列插入m
中的col
; - 右移
m
的其余列,以免丢失任何数据.
- increase the number
n
of columns of the matrixm
by 1; - insert the content of a vector
b
inm
as a new column, at indexcol
; - 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:
- 如果要在本地更新数据,则
- 矩阵
m
必须是可分配的 - 最好使用至少符合2003标准的编译器,这样您就可以访问固有的
move_alloc
,从而避免了在数组中复制一个数组.
- matrix
m
must beallocatable
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.
这是一个演示实现:
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
这篇关于将向量插入矩阵的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文