使用for循环转换矩阵



我正在尝试创建一个用于转置给定矩阵的代码:

我来自Matlab,我创建了以下代码:

A = [1,2,3,0,-2,0 ; 0,2,0,1,2,3];
n = size(A);
for i=1:n(2)
for j=1:n(1)
M(i,j) = A(j,i) 
end
end

在Python中,我正在尝试这个:

M = [
[1,2,3,0,-2,0],
[0,2,0,1,2,3]
]
LM = (len(M),len(M[0]))
print(LM)
Maux=[[]]
print(Maux)

for i in range(0,LM[1]):
for j in range(0,LM[0]):
Maux[i][j] = M[j][i]
print(Maux)

但当我编译时,错误是:

Maux[i][j]=M[j][i]IndexError:列表分配索引超出范围

知道吗?

如果要在python中使用矩阵,应该使用numpy(https://numpy.org/install/),它允许常规python列表所没有的常见向量操作,并且速度快得多。要回答你的问题,这应该能解决你的问题。

import numpy as np 
M = [
[1,2,3,0,-2,0],
[0,2,0,1,2,3]
]
#create numpy array
M_np = np.array(M)
#transpose numpy array
M_np_aux = M_np.T
#make it into a list (not recommended to make into list again)
Maux = M_np_aux.tolist()
print(M)
print(Maux)

最新更新