-->

如何转换在MATLAB一个2X2矩阵,以4X4矩阵?(How do I convert a 2X2

2019-09-02 04:51发布

我需要在一个2X2矩阵转换成以下方式4x4矩阵一些帮助:

A = [2 6;
     8 4]

应该变成:

B = [2 2 6 6;
     2 2 6 6;
     8 8 4 4;
     8 8 4 4]

我会怎么做呢?

Answer 1:

A = [2 6; 8 4];
% arbitrary 2x2 input matrix

B = repmat(A,2,2);
% replicates rows & columns but not in the way you want

B = B([1 3 2 4], :);
% swaps rows 2 and 3

B = B(:, [1 3 2 4]);
% swaps columns 2 and 3, and you're done!


Answer 2:

在MATLAB(R2015a及更高版本)要做到这一点最简单的方法的较新版本使用repelem功能:

B = repelem(A, 2, 2);

对于旧版本,其他(主要是)基于索引的解决方案很短的替代方案是使用功能kronones

>> A = [2 6; 8 4];
>> B = kron(A, ones(2))

B =

     2     2     6     6
     2     2     6     6
     8     8     4     4
     8     8     4     4


Answer 3:

可以做到比Jason的解决方案更容易:

B = A([1 1 2 2], :);  % replicate the rows
B = B(:, [1 1 2 2]);  % replicate the columns


Answer 4:

另外还有一个解决方案:

A = [2 6; 8 4];
B = A( ceil( 0.5:0.5:end ), ceil( 0.5:0.5:end ) );

它使用索引做的一切,不依赖于规模或A的形状



Answer 5:

这工作:

A = [2 6; 8 4];
[X,Y] = meshgrid(1:2);
[XI,YI] = meshgrid(0.5:0.5:2);
B = interp2(X,Y,A,XI,YI,'nearest');

这是从X A(X,Y)的只是二维最近邻插值,Y∈{1,2}的x,y∈{0.5,1,1.5,2}。

编辑 :Springboarding掉杰森S和马亭的解决方案,我想这大概是最短和最明确的解决方案:

A = [2 6; 8 4];
B = A([1 1 2 2], [1 1 2 2]);


Answer 6:

下面是基于简单的索引的方法,对于任意矩阵的作品。 我们希望每一个元素被扩展到M×N的子矩阵:

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

例:

>> 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

要查看方法的工作原理,让我们在索引一探究竟。 我们从连续数字的简单行向量

>> m=3; 1:m

ans =

     1     2     3

接下来,我们将其扩展到一个矩阵,通过重复它M次在第一维

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

I =

     1     2     3
     1     2     3
     1     2     3
     1     2     3

如果我们用一个矩阵来索引的阵列,则矩阵元素被连续使用在标准Matlab的顺序:

>> I(:)

ans =

     1
     1
     1
     1
     2
     2
     2
     2
     3
     3
     3
     3

最后,索引的阵列的情况下,“结束”的关键字的计算结果为在相应尺寸的阵列的大小。 其结果是,在以下的例子中是等效的:

>> 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])


Answer 7:

有一种重塑()函数,可以让你做到这一点...

例如:

reshape(array, [64, 16])

你可以找到一个伟大的视频教程在这里

干杯



文章来源: How do I convert a 2X2 matrix to 4X4 matrix in MATLAB?