How are two matrices multiplied according to the math rules: Khan Academy (base) C:\Users\ashish>python Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> a = [[1, -1], [1, 2]] >>> b = [[3], [4]] >>> a * b Traceback (most recent call last): File "[stdin]", line 1, in [module] TypeError: can't multiply sequence by non-int of type 'list' >>> a = np.array(a) >>> b = np.array(b) >>> a array([[ 1, -1], [ 1, 2]]) >>> b array([[3], [4]]) >>> np.matmul(a,b) array([[-1], [11]]) >>> np.matmul(b, a) Traceback (most recent call last): File "[stdin]", line 1, in [module] ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0) >>> a.dot(b) array([[-1], [11]]) >>> np.dot(a, b) array([[-1], [11]]) >>> a.b Traceback (most recent call last): File "[stdin]", line 1, in [module] AttributeError: 'numpy.ndarray' object has no attribute 'b' >>> np.dot(b, a) Traceback (most recent call last): File "[stdin]", line 1, in [module] ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0) # How about an element to element multiplication? # Note: this is not how math books do it >>> np.multiply(a, b) array([[ 3, -3], [ 4, 8]]) >>> np.multiply(b, a) array([[ 3, -3], [ 4, 8]]) >>> a*b array([[ 3, -3], [ 4, 8]]) >>> a = [[1, 1], [2, 2]] >>> b = [[0, 0], [1, 1]] >>> a = np.array(a) >>> b = np.array(b) >>> a*b array([[0, 0], [2, 2]]) >>> a = [[0, 1], [2, 3]] >>> a = np.array(a) >>> b = [[5, 10], [15, 20]] >>> b = np.array(b) >>> a*b array([[ 0, 10], [30, 60]]) >>> Ref: docs.scipy.org
Friday, September 3, 2021
Two Types of Matrix Multiplication Using NumPy
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment