user1050619
user1050619

Reputation: 20896

numpy multiplication table ouptut

Im a newbie to numpy and trying to find a efficient way to write mult table using numpy.

def mult_table():
    result = []
    for i in a:
        for j in a:
            result.append(i*j)
    return result

In numpy I see a dot matrix and a matmul but not sure how to replicate the above logic.

Upvotes: 2

Views: 4825

Answers (1)

jpp
jpp

Reputation: 164773

One way is to use numpy.arange. You can easily wrap this in a function.

import numpy as np

def mult_table(n):
    rng = np.arange(1, n+1)
    return rng * rng[:, None]

print(mult_table(5))

# [[ 1  2  3  4  5]
#  [ 2  4  6  8 10]
#  [ 3  6  9 12 15]
#  [ 4  8 12 16 20]
#  [ 5 10 15 20 25]]

Upvotes: 11

Related Questions