diva
diva

Reputation: 249

matrix multiplication with a constant

How can I multiply the following 1x1x3 matrix with a constant value (scalar):

a = [[[1, 2, 3]]]

For example, multiplying a by 3 should produce the following:

a*3 = [[[3,6,9]]]

Upvotes: 2

Views: 10894

Answers (4)

NPE
NPE

Reputation: 500447

Here is a way to do it using pure Python:

a3 = [[[el * 3 for el in col] for col in row] for row in a]

This works with 3D matrices of any shape, not just 1x1x3.

However, if this is the sort of thing you need to do on a regular basis, I would encourage you to learn NumPy. Then you'll be able to write:

a3 = a * 3

Upvotes: 1

MAK
MAK

Reputation: 26586

Here's one way using list comprehensions:

>>> a = [[[1, 2, 3]]]
>>> b = [[x*3 for x in a[0][0]]]
>>> b
[[3, 6, 9]]

Upvotes: 1

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29111

Try:

a= [[[1, 2, 3]]]
for i in range(len(a[0][0])):
    a[0][0][i] *= 3

print a    

Upvotes: 1

root
root

Reputation: 80346

Use NumPy:

In [1]: import numpy as np

In [2]: a = np.array([[[1, 2, 3]]])

In [3]: a
Out[3]: array([[[1, 2, 3]]])

In [4]: a*3
Out[4]: array([[[3, 6, 9]]])

Upvotes: 5

Related Questions