How to implement element-wise addition,subtraction and multiplication in Numpy?
Array is a collection of similar data elements. When you implement the arithmetic operations, you have to do each element. Let us implement this as follows.
Element-wise Arithmetic Operations in Numpy:
It starts
from importing numpy library. First, two arrays are included as input. Element
wise operations are performed and result is printed.
Code:
import numpy as np1
# Two arrays as input
s_arr1 = np1.array([11, 22, 33, 44])
s_arr2 = np1.array([5, 10, 15, 20])
# Arithmetic operations on element wise
print("Element wise Arithmetic Operations:")
print("Addition:", s_arr1 + s_arr2)
print("Subtraction:", s_arr2 - s_arr1) print("Multiplication:", s_arr1 *
s_arr2)
Output:
Element wise Arithmetic Operations:
Addition: [16 32 48 64]
Subtraction: [ -6 -12 -18 -24]
Multiplication: [ 55 220 495 880]
Element‑wise operations differ from matrix multiplication:
This
program gives you the difference from Matrix multiplication.
Code:
import numpy as np1
# input of two 2D arrays (matrices)
A = np1.array([[4, 5],
[6, 7]])
B = np1.array([[1, 2],
[3, 4]])
# Element-wise Arithmetic operations
print("Addition:\n", A + B)
print("Subtraction:\n", B - A)
print("Element-wise Multiplication:\n", A * B)
# Matrix multiplication (dot product)
print("Matrix Multiplication:\n", np1.dot(A, B))
Output:
Addition:
[[ 5 7]
[ 9 11]]
Subtraction:
[[-3 -3]
[-3 -3]]
Element-wise Multiplication:
[[ 4 10]
[18 28]]
Matrix Multiplication:
[[19 28]
[27 40]]
These are the ways to implement the element-wise operations
in arrays. Hope, you understood the concept. Keep coding!!!
Comments
Post a Comment