How to multiply two vector and get a matrix?

Learn, how to multiply two vector and get a matrix in Python? By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given two vectors (say A and B). size of A is 4 X 1 and that of B is 1 X 5. We need to multiply these vectors and get a matrix as a result.

Multiplying two vectors and get a matrix

For this purpose, we will use numpy.matmul() which is used to compute the matrix product of two arrays. It takes the input of two arrays and another parameter called out which is also a ndarray which is the location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m).

Finally, it returns the matrix product of the inputs. This is a scalar only when both arr1, arr2 are 1-d vectors otherwise it creates the desired shape. In our case, the desired shape will be 4 X 5.

Let us understand with the help of an example,

Python code to multiply two vector and get a matrix

# Import numpy
import numpy as np

# Creating two numpy arrays
arr1 = np.array([[1],[2],[3],[4]])
arr2 = np.array([[1,1,1,1,1],])

# Display original arrays
print("Original Array 1:\n",arr1,"\n")
print("Original Array 2:\n",arr2,"\n")

# Multiplying both vectors
res = np.matmul(arr1, arr2)
# Display result
print("Result:\n",res,"\n","\nShape:\n",res.shape)

Output

Example: How to multiply two vector and get a matrix?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.