【问题标题】:Expanding each element in a (2-by-2) matrix to a (3-by-2) block将 (2×2) 矩阵中的每个元素扩展为 (3×2) 块
【发布时间】:2016-12-27 08:39:15
【问题描述】:

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

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 中的位置相同。

这是 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)); 

感谢您的帮助。提前致谢。

【问题讨论】:

  • X 是[[1,2],[3,4]] 还是[[1,3],[2,4]]

标签: matlab python-3.x numpy matrix


【解决方案1】:

如果您可以在 Python 中使用 NumPy module,您可以使用 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 中如何以一种优雅和专业的方式实现预期结果的直接翻译,如下所示 -

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

【讨论】:

  • 这很好,它完全解决了我的问题。谢谢。
  • @percusse 这意味着幽默类似于问题中提到的professional 部分。所以,请不要认真阅读它:)
  • @Divakar 啊好吧,这只是一种好奇心 :)
【解决方案2】:

使用ndarray.repeat 的另一种方法:

>>> X = np.arange(4).reshape(2,2)+1
>>> X.repeat(3, axis=0).repeat(2, axis=1)
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]])

【讨论】:

  • 我认为这是更惯用的方法。 numpy.repeat 是专门为此任务设计的。 numpy.kron 可以,但我认为这是一种不太直接的方法。
  • 另请注意,您可以np.arange(1, 5)
猜你喜欢
  • 1970-01-01
  • 2016-05-08
  • 2018-07-18
  • 1970-01-01
  • 2021-12-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多