gpt4 book ai didi

python - 如何 reshape 一个矩阵,然后将其乘以另一个矩阵,然后在 python 中再次 reshape 它

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:03 24 4
gpt4 key购买 nike

我在将 python 与矩阵乘法和 reshape 结合使用时遇到问题。例如,我有一个大小为 (16,1) 的列 S 和一个大小为 (4,4) 的矩阵 H ,我需要将 S 列 reshape 为 (4,4) 以便将其与 H 相乘,然后 reshape 它再次进入 (16,1),我在 matlab 中做了如下操作:

clear all; clc; clear
H = randn(4,4,16) + 1j.*randn(4,4,16);
S = randn(16,1) + 1j.*randn(16,1);
for ij = 1 : 16
y(:,:,ij) = reshape(H(:,:,ij)*reshape(S,4,[]),[],1);
end
y = mean(y,3);

来到 python :

import numpy as np 

H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16)
S = np.random.randn(16,) + 1j * np.random.randn(16,)
y = np.zeros((4,4,16),dtype=complex)
for ij in range(16):
y[:,:,ij] = np.reshape(h[:,:,ij]@S.reshape(4,4),16,1)

但是我在这里得到一个错误,我们不能将大小为 256 的矩阵 y reshape 为 16x1。

有没有人知道如何解决这个问题?

最佳答案

只需这样做:

S.shape = (4,4)
for ij in range(16):
y[:,:,ij] = H[:,:,ij] @ S
S.shape = -1 # equivalent to 16

关于python - 如何 reshape 一个矩阵,然后将其乘以另一个矩阵,然后在 python 中再次 reshape 它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com