(Sum elements column by column) Write a function that returns the sum of all the elements in a specified column in a matrix using the following header:
def sumColumn(m, columnIndex):
Write a test program that reads a 3 x 4 matrix and displays the sum of each column.
Here is a sample run:
Enter a 3-by-4 matrix row for row 0: 1.5 2 3 4
Enter a 3-by-4 matrix row for row 1: 5.5 6 7 8
Enter a 3-by-4 matrix row for row 2: 9.5 1 3 1
Sum of the elements for column 0 is 16.5
Sum of the elements for column 1 is 9.0
Sum of the elements for column 2 is 13.0
Sum of the elements for column 3 is 13.0
Sum elements column by column Program Code:
# Function to calculate the sum of elements in a specified column of a matrix
def sumColumn(m, columnIndex):
total = 0
for row in m:
total += row[columnIndex]
return total
# Test program
def main():
matrix = [] # Initialize an empty matrix
# Prompt the user to enter a 3x4 matrix
for i in range(3):
row = input(f"Enter a 3-by-4 matrix row for row {i}: ").split()
row = [float(num) for num in row] # Convert the input numbers to floats
matrix.append(row)
# Display the sum of each column
for j in range(4):
columnSum = sumColumn(matrix, j)
print(f"Sum of the elements for column {j} is {columnSum}")
# Call the test program
main()
Executed Output:
Enter a 3-by-4 matrix row for row 0: 1.5 2 3 4
Enter a 3-by-4 matrix row for row 1: 5.5 6 7 8
Enter a 3-by-4 matrix row for row 2: 9.5 1 3 1
Sum of the elements for column 0 is 16.5
Sum of the elements for column 1 is 9.0
Sum of the elements for column 2 is 13.0
Sum of the elements for column 3 is 13.0