Asterisks ("*") no longer performs element-wise multiplication

Can you summarize your question or observation?

Here is the problem:

:green_square: numpy.matrix

A specialized 2D array:

  • Always 2D, even if you try to create 1D or 3D versions.
  • Overloads * to mean matrix multiplication, not element-wise multiplication.
  • Mostly kept for legacy reasons and compatibility with older code.

Use numpy.array instead

3 Likes

Test code:

import inspect

import numpy as np


def nparray_elementwise_multiply(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    (n, m) = a.shape
    assert a.shape == b.shape, "Shapes of 'a' and 'b' must match"
    result = np.zeros((n, m))
    for i in range(n):
        for j in range(m):
            result[i, j] = a[i, j] * b[i, j]
    return result


# time complexity of matrix multiplication tends to O(n^2.3729) but
# we can't use that 😂

def npmatrix_matrix_multiply(a: np.matrix, b: np.matrix) -> np.matrix:
    (na, ma) = a.shape
    (nb, mb) = b.shape
    assert ma == nb, "Number of columns of 'a' must match number of columns of 'b'"
    result = np.matrix(np.zeros((na, mb)))
    for i in range(na):
        for j in range(mb):
            for k in range(ma):
                result[i, j] += a[i, k] * b[k, j]
    return result


def test_nparray_star_operator(verbose: bool) -> None:
    a = np.array([[1, 2], [3, 4]])
    b = np.array([[3, 7], [1, 2]])
    one_way = nparray_elementwise_multiply(a, b)
    other_way = a * b  # ELEMENTWISE MULTIPLICATION
    assert one_way.shape == other_way.shape
    assert np.allclose(one_way, other_way)
    if verbose:
        print(f"{inspect.currentframe().f_code.co_name} passes")


def test_npmatrix_star_operator(verbose: bool) -> None:
    a = np.matrix([[1, 2], [3, 4]])
    b = np.matrix([[3, 7], [1, 2]])
    one_way = npmatrix_matrix_multiply(a, b)
    other_way = a * b  # MATRIX MULTIPLICATION
    assert one_way.shape == other_way.shape
    assert np.allclose(one_way, other_way)
    if verbose:
        print(f"{inspect.currentframe().f_code.co_name} passes")


test_nparray_star_operator(True)
test_npmatrix_star_operator(True)
2 Likes