'Transpose a matrix using for loops

I'm trying to create a code for transpose a given matrix:

I come from Matlab, and I create this code:

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

In Python I'm tryng this:

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)

But when I compile, the error is:

Maux[i][j] = M[j][i] IndexError: list assignment index out of range

Any idea?



Solution 1:[1]

If you are going to work with matrixes in python you should use numpy ( https://numpy.org/install/), it allows for common vector operations that regular python lists don't and is much faster. To answer you question this should solve your problem.

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Love Eklund