-1

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!

  • 4
    Your `B` is correct. You're printing the matrix after appending each row which is why you're seeing that -- notice the last print is your expected diagonal matrix. – erip Feb 23 '22 at 13:16

4 Answers4

0

Can you use numpy? It works like this:

import numpy as np

scalar = 5

a = [[1, 0, 0],
     [0, 1, 0],
     [0, 0, 1]]
print(np.array(a) * scalar)
Michel Kok
  • 354
  • 1
  • 10
0

Without relying on another module/library, your best bet is to handle the printing outside the loop. Here's one way to do it:

for row in B:
    print(row)
eccentricOrange
  • 876
  • 5
  • 18
  • 1
    BTW, it seems that you're mixing up the `m` and `n` variables. You won't notice this straightaway because their values are the same. – eccentricOrange Feb 23 '22 at 13:21
  • The OP is not mixing them up. `i` corresponds to the row number, `j` corresponds to the column number. – erip Feb 23 '22 at 13:26
  • 1
    @erip OP used `n` as the argument to `range()` for both their loops (instead of `n` for one and `m` for another, which I believe was the intention). – eccentricOrange Feb 23 '22 at 13:27
0

My solution:

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


for row_index,row in enumerate(A):
    for column_index,column in enumerate(row):
        A[row_index][column_index] *= scalar

for i in A:
    print(i)

Output:

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

Note: I didn´t use B at all.

Leo Eiji
  • 54
  • 6
0

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]
  • No Problem. As someone else also pointed out, you would want to incorporate both m and n to the for loops' range functions. For consistency's sake... – Brendan Lydon Mar 01 '22 at 13:37