0

I am new to python but have experience in MatLab. I am trying to write a module to create an identity matrix (i.e. I = [[1,0],[0,1]]) of a given size without using numpy for a piece of an assignment. I have attempted to do so with the following code:

    Q = []
    b = []
    
    row = 2
    col = 2

    for i in range(row):
        b.append(0)
    for j in range(row):
        Q.append(b)

    for n in range(col):
        Q[n][n] = 1

My idea here was first to create a matrix of zeros "Q" and then assign ones to the diagonal entries. However, when I run this code, it creates a matrix Q = [[1,1],[1,1]]. I have also tried to be a bit more specific by writing:

    for m in range(row):
        for n in range(col):
            if m == n:
                Q[m][n] = 1
            else:
                Q[m][n] = 0

Which gives a different matrix Q = [[0,1],[0,1]]. I'm assuming my issue is coming from the code used to create Q, but I don't entirely understand how matrices work in python. Any help would be greatly appreciated! Thank you.

  • `Q.append(b)` is not appending copies of `b`. They are references to the one and only single list `b`. The concept of references will likely be new to you coming from matlab, where you get implied copies everywhere, but it's an important concept. – Mikael Öhman Oct 05 '22 at 21:38

2 Answers2

1

You can use list comprehension for this assignment, which allows you to enclose everything in one line:

n = 4  # Number of rows and columns in the matrix.
identity = [[0] * i + [1] + [0] * (n - i - 1) for i in range(n)]
1

When you do Q.append(b), you are adding the same list every time. When you access a row with Q[...], you always access the same list, so you progressively modify the single list you have.

Try creating one new list per row.

Cheers!

Pietro
  • 1,090
  • 2
  • 9
  • 15