NumPy: Add elements in a matrix, do not add an element below an element if it is 0
Add Elements Conditionally
Write a NumPy program to add elements to a matrix. If an element in the matrix is 0, we will not add the element below this element.
This problem involves writing a NumPy program to add elements in a matrix with a specific condition: if an element in the matrix is 0, the element directly below it should not be added. The task requires iterating through the matrix and selectively summing elements based on the given condition. This program demonstrates conditional summation within a matrix using NumPy's array manipulation capabilities.
Sample Solution :
Python Code :
Output:
Original matrix: [[1, 1, 0, 2], [0, 3, 0, 3], [1, 0, 4, 4]] Sum: 14
Explanation:
In the above code -
def sum_matrix_Elements(m): This statement defines the function sum_matrix_Elements(m) that takes a nested list (representing a matrix) as its input argument.
arra = np.array(m): This statement converts the input nested list 'm' into a NumPy 2D array named 'arra'.
element_sum = 0: This statement initializes a variable 'element_sum' to store the sum of the matrix elements, initially set to 0.
The nested for loops (for p in range(len(arra)): and for q in range(len(arra[p])):) iterate over each element in the 2D array 'arra'.
if arra[p][q] == 0 and p < len(arra)-1:: This statement checks if the current element 'arra[p][q]' is 0 and if it's not in the last row of the array.
arra[p+1][q] = 0: If the above condition is True, it sets the element below the current element to 0.
element_sum += arra[p][q]: This statement adds the current element value to the 'element_sum'.
return element_sum: This statement returns the calculated sum of the matrix elements.
For more Practice: Solve these Related Problems:
- Add elements to a matrix conditionally based on the value of the element above them.
- Implement conditional addition to rows of a matrix when a threshold value is met.
- Add two matrices element-wise only if the corresponding element in the first matrix is non-zero.
- Update a matrix by conditionally adding a vector only where the matrix elements exceed a specified limit.
Go to:
PREV : Convert NumPy Dtypes to Python Types
NEXT : Find Missing Data in Array
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.