如何构造一个包含 9 个较小矩阵的矩阵 [英] How to construct a matrix containing 9 smaller matrix

查看:26
本文介绍了如何构造一个包含 9 个较小矩阵的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有九个矩阵,其维度为 (N x N)<代码>A1(i,j),A2(i,j),A3(i,j),A4(i,j),A5(i,j),A6(i,j),A7(i,j),A8(i,j),A9(i,j)

I have nine matrices whose dimension as (N by N) A1(i,j),A2(i,j),A3(i,j),A4(i,j),A5(i,j),A6(i,j),A7(i,j),A8(i,j),A9(i,j)

然后我想构造一个更大的矩阵(3N x 3N),包括这九个矩阵:

Then I want to construct a larger matrix (3N by 3N) including these nine matrices as:

A = [A1 A2 A3
     A4 A5 A6
     A7 A8 A9]

在fortran中,我可以使用命令行吗

In fortran, can I use the command line as

do i=1,FN
   do j=1,FML
      A(i,j) = [A1(i,j),A2(i,j),A3(i,j);A4(i,j),A5(i,j),A6(i,j);A7(i,j),A8(i,j),A9(i,j)]
   end do
end do

推荐答案

为了好玩,你也可以用do-loops做大A矩阵

Just for fun, you can also make the large A matrix by using do-loops as

do i = 1, N
    A( i,       : ) = [ A1( i,: ), A2( i,: ), A3( i,: ) ]
    A( i + N,   : ) = [ A4( i,: ), A5( i,: ), A6( i,: ) ]
    A( i + N*2, : ) = [ A7( i,: ), A8( i,: ), A9( i,: ) ]
enddo

它以行主要方式填充 A 矩阵,因此小矩阵也以这种方式出现.如果真的有必要,这也可以写成单行

which fills the A matrix in row-major way and so the small matrices also appear in that way. If really really necessary, this could also be written as one-liner as

A = transpose( reshape(  &
        [ ( [ A1( i,: ), A2( i,: ), A3( i,: ) ], i=1,N ), &
          ( [ A4( i,: ), A5( i,: ), A6( i,: ) ], i=1,N ), &
          ( [ A7( i,: ), A8( i,: ), A9( i,: ) ], i=1,N ) ], [N*3, N*3] ))

原来是@francescalus 答案中第二个数组构造函数的转置(单行形式)

which turns out to be the transpose of the second array constructor in the @francescalus answer (in one-liner form)

A = reshape(  &
        [ ( [ A1( :,i ), A4( :,i ), A7( :,i ) ], i=1,N ), &
          ( [ A2( :,i ), A5( :,i ), A8( :,i ) ], i=1,N ), &
          ( [ A3( :,i ), A6( :,i ), A9( :,i ) ], i=1,N ) ], [N*3, N*3] )

<小时>

为了更进一步,我们可以像在其他语言中一样定义 hcatvcat 例程(注意这里需要显式接口):


To go one-step further, we may define hcat and vcat routines as in other languages (note here that explicit interface is necessary):

function hcat( A, B, C ) result( X )
    integer, dimension(:,:) :: A, B, C
    integer :: X( size(A,1), size(A,2)+size(B,2)+size(C,2) )

    X = reshape( [ A, B, C ], shape( X ) )
endfunction

function vcat( A, B, C ) result( X )
    integer, dimension(:,:) :: A, B, C
    integer :: X( size(A,1)+size(B,1)+size(C,1), size(A,2) )

    X = transpose( reshape( &
            [ transpose(A), transpose(B), transpose(C) ], &
            [ size(X,2), size(X,1) ] ) )
endfunction

那么我们可以写

A = vcat( hcat( A1, A2, A3 ), hcat( A4, A5, A6 ), hcat( A7, A8, A9 ) )

这有点类似于问题中所需的形式:

which is somewhat more similar to the desired form in the question:

A = [ A1 A2 A3 ; A4 A5 A6 ; A7 A8 A9 ]

这篇关于如何构造一个包含 9 个较小矩阵的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆