Search code examples
pythonmatrix-multiplicationscalar

(Python) Can't get matrix scalar multiplication output correct


I'm trying to multiply a matrix by scalar, but I'm unable to get my output right.

  m, n = 3, 3
scalar = 5
A = [ [1, 0, 0],
      [0, 1, 0],
      [0, 0, 1] ]
B = []


for i in range(n):
    B.append([])
    for j in range(n):
        B[i].append(A[i][j] * scalar)
    print (B)

The output I receive is:

[[5, 0, 0]]
[[5, 0, 0], [0, 5, 0]]
[[5, 0, 0], [0, 5, 0], [0, 0, 5]]

My desired output would be:

[ [5, 0, 0],
  [0, 5, 0],
  [0, 0, 5] ]

How do I get there?

Edit: Your advice worked, thanks all!


Solution

  • You were very close! Here is my solution

    A = [[1,0,0], [0,1,0], [0,0,1]]
    B = []
    m,n = 3,3
    scalar = 5
    for i in range(n):
       B.append([])
       for j in range(n):
          result = A[i][j] * scalar
          B[i].append(result)
    #B = [[5, 0, 0], [0, 5, 0], [0, 0, 5]]
    for i in B:
       print(i)
    

    And, then your output is:

    [5, 0, 0]
    [0, 5, 0]
    [0, 0, 5]