NumPy: Check whether the dimensions of two given arrays are same or not
Check if dimensions of two arrays match.
Write a NumPy program to check whether the dimensions of two given arrays are same or not.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Defining a function to check array dimensions
def test_array_dimensions(ar1, ar2):
try:
# Attempting to add arrays ar1 and ar2
ar1 + ar2
except ValueError:
# If ValueError occurs (arrays have different dimensions), return "Different dimensions"
return "Different dimensions"
else:
# If no error occurs (arrays have the same dimensions), return "Same dimensions"
return "Same dimensions"
# Creating two NumPy arrays: ar1 and ar2 reshaped into a 4x5 array
ar1 = np.arange(20).reshape(4, 5)
ar2 = np.arange(20).reshape(4, 5)
# Testing array dimensions for ar1 and ar2 using the defined function
print(test_array_dimensions(ar1, ar2))
# Creating two NumPy arrays: ar1 and ar2 reshaped into a 5x4 and 4x5 arrays respectively
ar1 = np.arange(20).reshape(5, 4)
ar2 = np.arange(20).reshape(4, 5)
# Testing array dimensions for ar1 and ar2 using the defined function
print(test_array_dimensions(ar1, ar2))
Sample Output:
Same dimensions Different dimensions
Explanation:
The above code defines a function called 'test_array_dimensions()' that checks whether two input arrays have the same dimensions (i.e., can be added element-wise) and returns a string indicating the result.
- The function takes two input arguments, 'ar1' and 'ar2', which are NumPy arrays.
- A try block is used to attempt adding 'ar1' and 'ar2' element-wise using the + operator. If the dimensions of the arrays are compatible for addition, the operation will be executed without any issues.
- If the dimensions of the arrays are not compatible for addition, a ValueError will be raised. In this case, the code inside the except ValueError block will be executed, returning the string "Different dimensions".
- If the addition is successful and no ValueError is raised, the code inside the else block will be executed, returning the string "Same dimensions".
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics