How do I convert a 2X2 matrix to 4X4 matrix in MATLAB?

后端 未结 7 1017
無奈伤痛
無奈伤痛 2020-12-03 23:26

I need some help in converting a 2X2 matrix to a 4X4 matrix in the following manner:

A = [2 6;
     8 4]

should become:

B =         


        
7条回答
  •  甜味超标
    2020-12-04 00:14

    Here's a method based on simple indexing that works for an arbitrary matrix. We want each element to be expanded to an MxN submatrix:

    A(repmat(1:end,[M 1]),repmat(1:end,[N 1]))
    

    Example:

    >> A=reshape(1:6,[2,3])
    
    A =
    
         1     3     5
         2     4     6
    
    >> A(repmat(1:end,[3 1]),repmat(1:end,[4 1]))
    
    ans =
    
         1     1     1     1     3     3     3     3     5     5     5     5
         1     1     1     1     3     3     3     3     5     5     5     5
         1     1     1     1     3     3     3     3     5     5     5     5
         2     2     2     2     4     4     4     4     6     6     6     6
         2     2     2     2     4     4     4     4     6     6     6     6
         2     2     2     2     4     4     4     4     6     6     6     6
    

    To see how the method works, let's take a closer look at the indexing. We start with a simple row vector of consecutive numbers

    >> m=3; 1:m
    
    ans =
    
         1     2     3
    

    Next, we extend it to a matrix, by repeating it M times in the first dimension

    >> M=4; I=repmat(1:m,[M 1])
    
    I =
    
         1     2     3
         1     2     3
         1     2     3
         1     2     3
    

    If we use a matrix to index an array, then the matrix elements are used consecutively in the standard Matlab order:

    >> I(:)
    
    ans =
    
         1
         1
         1
         1
         2
         2
         2
         2
         3
         3
         3
         3
    

    Finally, when indexing an array, the 'end' keyword evaluates to the size of the array in the corresponding dimension. As a result, in the example the following are equivalent:

    >> A(repmat(1:end,[3 1]),repmat(1:end,[4 1]))
    >> A(repmat(1:2,[3 1]),repmat(1:3,[4 1]))
    >> A(repmat([1 2],[3 1]),repmat([1 2 3],[4 1]))
    >> A([1 2;1 2;1 2],[1 2 3;1 2 3;1 2 3;1 2 3])
    >> A([1 1 1 2 2 2],[1 1 1 1 2 2 2 2 3 3 3 3])
    

提交回复
热议问题