Transpose a matrix using for loops (only)

Question:

I’m trying to create a code for transpose an array

I come from Matlab, and I create this code (wich works well):

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 (using the same logic):

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

And I know using numpy I can create this code as well:

import numpy as np 

A = [

    [1,2,3,0,-2,0],
    [0,2,0,1,2,3]

    ]

T = np.transpose(A)

print(A)
print(T)

But I need create this code only using for loops, any idea?

Asked By: Cain9745

||

Answers:

Maux=[[]]

is a list containing a single empty list. This has a shape of (1, 0) which is why you get a index out of bounds error. You need to initialize Maux to be the same shape as M. So something like

Maux = [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]]
Answered By: Inciarte

You need to initialize Maux to handle to transpose:

Maux=[[0 for i in range(len(M))] for j in range(len(M[0]))]

Your code, as is, is asking python to assign values to locations which do not exist (because Maux is empty lists).

In summary, you need to create Maux as an empty list of lists with the same dimensions as the transpose: if M is n by m, then Maux must be m by n not 1 by 0.

Answered By: Kraigolas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.