w3resource

NumPy: Compute the inner product of vectors for 1-D arrays and in higher dimension

NumPy: Linear Algebra Exercise-6 with Solution

Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension.

Sample Solution:

Python Code :

import numpy as np

# Create two 1-D arrays 'a' and 'b'
a = np.array([1, 2, 5])
b = np.array([2, 1, 0])

# Display the original 1-D arrays 'a' and 'b'
print("Original 1-d arrays:")
print(a)
print(b)

# Calculate the inner product of arrays 'a' and 'b' using np.inner()
result = np.inner(a, b)

# Display the inner product of the said vectors
print("Inner product of the said vectors:")
print(result)

# Create two 3x3 arrays 'x' and 'y'
x = np.arange(9).reshape(3, 3)
y = np.arange(3, 12).reshape(3, 3)

# Display the original higher-dimensional arrays 'x' and 'y'
print("Higher dimension arrays:")
print(x)
print(y)

# Calculate the inner product of arrays 'x' and 'y' using np.inner()
result = np.inner(x, y)

# Display the inner product of the said vectors
print("Inner product of the said vectors:")
print(result) 

Sample Output:

Original 1-d arrays:
[1 2 5]
[2 1 0]
Inner product of the said vectors:
Higher dimension arrays:
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
Inner product of the said vectors:
[[ 14  23  32]
 [ 50  86 122]
 [ 86 149 212]]

Explanation:

In the above code –

m = np.mat("3 -2;1 0"): This line creates a 2x2 NumPy matrix m with the elements:

[[ 3, -2],

[ 1, 0]]

w, v = np.linalg.eig(m): This line computes the eigenvalues and eigenvectors of the matrix m. The eig function takes a square matrix as input and returns two arrays: one containing the eigenvalues, and the other containing the corresponding eigenvectors as columns.

print( "Eigenvalues of the said matrix", w): This line prints the eigenvalues of the matrix m. In this case, the eigenvalues are 2.0 and 1.0.

print( "Eigenvectors of the said matrix", v): This line prints the eigenvectors of the matrix m as columns of the v array. The eigenvectors corresponding to the eigenvalues 2.0 and 1.0 are [[-0.89442719, 0.70710678], [-0.4472136 , -0.70710678]].

Python-Numpy Code Editor:

Previous: Write a NumPy program to evaluate Einstein’s summation convention of two given multidimensional arrays.
Next: Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/linear-algebra/numpy-linear-algebra-exercise-6.php