Home > Blockchain >  python iterate over arrays matrices
python iterate over arrays matrices

Time:05-26

I am trying to create a new matrix(array)

a = [1, 2, 3]

b = [0, 1, 2]

where

C = [[1*0, 1*1, 1*2], [2*0, 2*1, 2*2], [3*0, 3*1, 3*2]]

I have been scouring the documentation in numpy but can't find a function to satisfy this.

for i in a:
    c = np.multiply(a, b)
    for j in b:
        c = np.multiply(a, b)

CodePudding user response:

Consider your input and output. You want a 3x3 array from the multiplication of two arrays. That can happen when your input arrays are of the shape 3xn and nx3, where n is any integer. Specifically, for your case, you have 3x1 and 1x3 arrays.

So just convert the arrays to the right shape, and multiply them. Note that the @ represents matrix multiplication.

import numpy as np
a = np.array([1, 2, 3])
b = np.array([0, 1, 2])

c = a.reshape(3, 1) @ b.reshape(1, 3)
print(c)

CodePudding user response:

You're looking for numpy.matmul. You'll need to make the vectors have two dimensions (with a size of one in one of the dimensions). For example:

np.matmul(np.array([[1],[2],[3]]), np.array([[2,3,4]]))

CodePudding user response:

There are several ways. This is often called an outer product:

In [46]: a=np.array([1,2,3]); b=np.array([0,1,2])

In [47]: np.outer(a,b)
Out[47]: 
array([[0, 1, 2],
       [0, 2, 4],
       [0, 3, 6]])

Elementwise multiplication with broadcasting also works well:

In [48]: a[:,None]*b
Out[48]: 
array([[0, 1, 2],
       [0, 2, 4],
       [0, 3, 6]])

This multiplies a (N,1) array with a (M) to make a (N,M). But you need to read up on broadcasting.

It can also be done as matrix multiplication, by making (N,1) and (1,M) arrays (with sum on the size 1 dimension). Read the np.matmul docs for details.

In [49]: a[:,None]@b[None,:]
Out[49]: 
array([[0, 1, 2],
       [0, 2, 4],
       [0, 3, 6]])

For lists, the purely iterative solution is:

In [50]: [[i*j for j in b] for i in a]
Out[50]: [[0, 1, 2], [0, 2, 4], [0, 3, 6]]
  • Related