问题
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 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:
- 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.
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