w3resource

NumPy: Create an inner product of two arrays

NumPy Mathematics: Exercise-13 with Solution

Write a NumPy program to create an inner product of two arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array 'x' reshaped as a 3D array (2x3x4)
x = np.arange(24).reshape((2, 3, 4))

# Displaying the array 'x'
print("Array x:")
print(x)

# Creating a NumPy array 'y' containing a range of 4 elements
print("Array y:")
y = np.arange(4)

# Displaying the array 'y'
print(y)

# Computing the inner product between arrays 'x' and 'y'
print("Inner of x and y arrays:")
print(np.inner(x, y)) 

Sample Output:

Array x:                                                               
[[[ 0  1  2  3]                                                        
  [ 4  5  6  7]                                                        
  [ 8  9 10 11]]                                                       
                                                                       
 [[12 13 14 15]                                                        
  [16 17 18 19]                                                        
  [20 21 22 23]]]                                                      
Array y:                                                               
[0 1 2 3]                                                              
Inner of x and y arrays:                                               
[[ 14  38  62]                                                         
 [ 86 110 134]]

Explanation:

In the above code –

The inner() function computes the inner product of two arrays. For arrays with more than one dimension, it calculates the inner product along the last dimension of the first array. It also computes it along the second dimension of the second array. In this case, x has shape (2, 3, 4) and y has shape (4), so the inner function result will have shape (2, 3).

The inner product is computed as follows: for each element in the result, the corresponding elements of the last dimension of x and y are multiplied together, and the products are summed.

Pictorial Presentation:

NumPy Mathematics: Create an inner product of two arrays.

Python-Numpy Code Editor:

Previous: Write a NumPy program to multiply a matrix by another matrix of complex numbers and create a new matrix of complex numbers.
Next: Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.