Skip to content
Advertisement

Python Element-wise Multiplication

In MATLAB, I do a calculation using

JavaScript

Here, A and B are 1*19-sized matrices.

To execute the same code in Python, I am using the following code-

JavaScript

Upon running the code, I get the following error-

JavaScript

What should I do?

Advertisement

Answer

MATLAB’s .* is a broadcasting operator. It scalar-extends the * operator to apply to matrices of matching size pointwise. This is not matrix multiplication, which is a different operation available on matrices that requires the middle two dimensions to match.

The equivalent of .* in Python, assuming the left-hand and right-hand side are numpy arrays, is simply *.

JavaScript

If the left-hand and right-hand side are not numpy arrays (for instance, if they’re ordinary Python lists), then you can convert them by calling numpy.array on them beforehand

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement