[SOLVED] matrix multiplication in a customized way

Issue

I have a array of the size (3,):

a = [1,2,3]

and another array of the size (3,3):

b = [[1,2,3],[4,5,6],[7,8,9]]

I am looking for a vectorized way to multiply the a**2 (a^2) to b in a way to:

> a**2=[1,4,9]

multiplies that 1 to entire row 1 from matrix b
4 to the second row of the matrix b
and 9 to the entire row of the matrix b.

my final result has to be this:

> (a**2)*b = [[1,2,3],[16,20,24],[63,72,81]]

Thanks!

Solution

You must first makes a (1D: (3, )) and b (2D: (3, 3)) the same in terms of dimensions. So, it is needed to add a dimension to a, which can be done by one of the following methods:

a = a[:, None]                    # way 1
a = a[:, np.newaxis]              # way 2
a = np.expand_dims(a, axis=1)     # way 3

and then do your calculations on it as:

formula = a ** 2 * b

Note: as it is good explained in the comments of this answer, it is recommended to use way 2 or way 3 instead of way 1.

Answered By – Ali_Sh

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *