我正在嘗試將 2x2 矩陣的每個元素(例如 [1,1],[1,1])與 2x2 單位矩陣相乘。問題是 numpy 將整個單位矩陣作為一個單獨的子索引,這不是我需要進一步評估的結果,我希望它有 4 行和 4 列,但是當我將其重塑為 (4,4) 時,它偏移值,我在每一行上得到 [1,0,1,0](請參閱影像以獲取所需和獲得的結果)。謝謝! 圖片在這里
uj5u.com熱心網友回復:
歡迎來到 SO。對于以后的問題,請嘗試將代碼放在這里而不是鏈接影像,這樣會使事情變得更容易。
至于你的問題,你可以用np.tile. 例子:
import numpy as np
I = np.identity(2)
A = np.tile(I, [2, 2])
A的內容:
array([[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]])
這是假設要乘以身份的矩陣正好是 [[1 1][1 1]] 而不是任何 2x2 矩陣(我沒有完全理解你的問題的這一點)。如果可以是其他矩陣,請提供預期輸出的示例,因為可能有幾種可能的解決方案。
在您的示例之后編輯A = [2*I, 0*I],[4*(-I), 1*I]:
import numpy as np
# generate the tiled identity (see above)
M = np.tile(np.identity(2), [2, 2])
# now we choose which ones are going to be negatives, from your example:
V = np.array([[1, 1], [-1, 1]])
# now define the 2x2 input matrix
N = np.array([[2, 0], [4, 1]])
# finally, let's combine all this:
A = np.repeat(N * V, 4).reshape(-1, 4) * M
A的內容:
array([[ 2., 0., 2., 0.],
[ 0., 0., 0., 0.],
[-4., -0., -4., -0.],
[ 0., 1., 0., 1.]])
uj5u.com熱心網友回復:
看起來您想要 Kronecker 產品。
In [585]: np.kron(np.ones((2,2),int), np.eye(2,dtype=int))
Out[585]:
array([[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380557.html
