将(2 x 2)矩阵中的每个元素扩展为(3 x 2)块 [英] Expanding each element in a (2-by-2) matrix to a (3-by-2) block

查看:102
本文介绍了将(2 x 2)矩阵中的每个元素扩展为(3 x 2)块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python 3 ---具有专业而优雅的代码,将(2-by-2)矩阵中的每个元素扩展为(3-by-2)块.由于我不知道python代码,因此我只会在数学中描述以下内容

I want to expand each element in a (2-by-2) matrix to a (3-by-2) block, using Python 3 --- with professional and elegant codes. Since I don't know the python codes, I will just describe the following in maths

X =              # X is an 2-by-2 matrix.
     1, 2
     3, 4

d = (3,2)        # d is the shape that each element in X should be expanded to.
Y =              # Y is the result
     1, 1, 2, 2
     1, 1, 2, 2
     1, 1, 2, 2
     3, 3, 4, 4
     3, 3, 4, 4
     3, 3, 4, 4

并不是说X中的每个元素现在都是Y中的3×2块.Y中的块位置与X中的元素位置相同.

Not that every element in X is now an 3-by-2 block in Y. The position of the block in Y is the same as the position of the element in X.

这是MATLAB代码

X = [1,2;3,4];
d = [3,2]
[row, column] = size(X);
a = num2cell(X);
b = cell(row, column);
[b{:}] = deal(ones(d));

Y = cell2mat(cellfun(@times,a,b,'UniformOutput',false)); 

感谢您的帮助.预先感谢.

I appreciate your help. Thanks in advance.

推荐答案

如果可以使用 NumPy module 使用Python,则可以使用 numpy.kron -

If you are okay with using NumPy module with Python, you can use numpy.kron -

np.kron(X,np.ones((3,2),dtype=int))

样品运行-

In [15]: import numpy as np

In [16]: X = np.arange(4).reshape(2,2)+1 # Create input array

In [17]: X
Out[17]: 
array([[1, 2],
       [3, 4]])

In [18]: np.kron(X,np.ones((3,2),dtype=int))
Out[18]: 
array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [1, 1, 2, 2],
       [3, 3, 4, 4],
       [3, 3, 4, 4],
       [3, 3, 4, 4]])

实际上,这是如何以一种专业的专业方式MATLAB中达到预期结果的直接翻译,如下所示-

In fact, this is a direct translation of how one would achieved the desired result in MATLAB in an elegant and professional way as well, as shown below -

>> X = [1,2;3 4]
X =
     1     2
     3     4
>> kron(X,ones(3,2))
ans =
     1     1     2     2
     1     1     2     2
     1     1     2     2
     3     3     4     4
     3     3     4     4
     3     3     4     4

这篇关于将(2 x 2)矩阵中的每个元素扩展为(3 x 2)块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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