Scalar Multiplication in Numpy
Here, we use Scalar multiplications in different ways. Let us try three methods listed as follows..
- · 1D array scalar multiplication
- · 2D array scalar multiplication
- · Different scalars for each column
The sample code is given below.
1D array scalar multiplication:
This code multiplies
the array by 3. First, it creates an array of elements. Each element is
multiplied by 3. The result is displayed.
Code:
import numpy as np1
# Create an array with elements
s_arr = np1.array([1, 3, 5, 7, 9, 11, 13, 15])
# Scalar multiplication by 3
result = s_arr * 3
print("Original array:", s_arr)
print("Multiplied by 3:", result)
Output:
Original array: [ 1
3 5 7 9 11
13 15]
Multiplied by 3: [ 3
9 15 21 27 33 39 45]
2D array scalar multiplication:
It has two-dimensional
array. Each element is multiplied by 3. Finally, the output is displayed.
Code:
import numpy as np1
# Create a 2D array as matrix
s_matrix = np1.array([[1, 2, 1],
[3,
5, 4]])
# Multiply the matrix by 3
result = s_matrix * 3
print("Original matrix:\n", s_matrix)
print("Multiplied by 3:\n", result)
Output:
Original matrix:
[[1 2 1]
[3 5 4]]
Multiplied by 3:
[[ 3 6 3]
[ 9 15 12]]
Different scalars for each column:
This
method uses three different scalar values for each column. These values are
multiplied and displayed as output.
Code:
import numpy as np1
# Creation of 2D array
matrix = np1.array([[1, 2, 1],
[3,
5, 4]])
# Scalars for each column
scalars = np1.array([1, 2, 3])
# multiply each column by its scalar
result = matrix * scalars
print("Original matrix:\n", matrix)
print("Scalars per column:", scalars)
print("Result:\n", result)
Output:
Original matrix:
[[1 2 1]
[3 5 4]]
Scalars per column: [1 2 3]
Result:
[[ 1 4 3]
[ 3 10 12]]
These are the ways to implement scalar multiplication in
numpy using python. Hope, you understood the concept. Keep Coding!!!
Comments
Post a Comment