Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise multiplication in Python equivalent to Matlab

I would like to know whether there is an equivalent operation of elementwise multiplication in Python as there is to MATLAB. The answer is yes at first, however there is a specific functionality of the elementwise multiplication MATLAB that is every useful, which I cant seem to replicate in python.

In specific if we have matrices A and b in MATLAB, and we decide to implement elementwise multiplication, we get the following:

A = [1 2 3] ;
b = [1;
     2;
     3] ;

C = A.*b
C = [1*1 1*2 1*3 ;
     2*1 2*2 2*3 ;
     3*1 3*2 3*3] ;

As a python beginner, to perform the same operation in Python my instinct would be to extend the matrices so that they are of identical dimensions and then exploit the basic elementwise multiplication that python offers with numpy.

So is that correct?

like image 992
kostas1335 Avatar asked Apr 13 '26 21:04

kostas1335


2 Answers

For numerical processing, you should use NumPy. Refer to NumPy for Matlab users for help getting started. Here is how you would translate your Matlab code to Python/NumPy.

import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2, 3]).reshape(3, 1)
c = a * b
a.shape  # (3,)
b.shape  # (3, 1)

c
# array([[1, 2, 3],
#        [2, 4, 6],
#        [3, 6, 9]])

Of course, don't forget to install NumPy.

like image 89
jakub Avatar answered Apr 15 '26 11:04

jakub


With numpy, you can use a*b directly:

import numpy as np

a = np.array([1,2,3])
b = a.reshape((3,1))
C = a*b # or np.multiply(a,b)
print(C)

My output:

[[1 2 3]
 [2 4 6]
 [3 6 9]]
like image 37
wagnifico Avatar answered Apr 15 '26 11:04

wagnifico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!