I mainly need help with creating the 3 by 4 matrix (part 3 of the assignment) as i am confused as how i would create it. However this is the entire assignment:

  1. Write a function that returns the sum of all the elements in a specified column in a matrix using the following header:

    def sumColumn(matrix, columnIndex)

  2. Write a function that displays the elements in a matrix row by row, where the values in each row are displayed on a separate line (see the output below).

3.Write a test program (i.e., a main function) 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: 2.5 3 4 1.5
Enter a 3-by-4 matrix row for row 1: 1.5 4 2 7.5
Enter a 3-by-4 matrix row for row 2: 3.5 1 1 2.5

The matrix is
2.5 3.0 4.0 1.5
1.5 4.0 2.0 7.5
3.5 1.0 1.0 2.5

Sum of elements for column 0 is 7.5
Sum of elements for column 1 is 8.0
Sum of elements for column 2 is 7.0
Sum of elements for column 3 is 11.5

Show your code, and tell us what is not clear.

Hint, your matrix will be a list of 3 sublists, each sublist has 4 elements.

matrix34 = [
[2.5, 3.0, 4.0, 1.5],
[1.5, 4.0, 2.0, 7.5],
[3.5, 1.0, 1.0, 2.5]
]

Each sublist forms a row and each column has matching index number elements from each sublist. The index is zero based, so column one has index 0. The value in row three and column one is matrix34[2][0] --> 3.5

this is easy to do :

#!/usr/bin/env python
#-*- coding:utf-8 -*-

matirx = []
for i in xrange(3):
    print "Enter a 3-by 4 matrix row for row %d" % i
    row = map(float, raw_input().split(' '))
    matirx.append(row)

print "The matrix is"

for row in matirx:
    print row

revmatirx = map(list, zip(*matirx))

for i in xrange(4):
    print "Sum of elements for column %d is" % i
    print sum(revmatirx[i])

Also, if this is just an exercise, then doing it with native python datastructures (like lists) is a nice way to go. In reality, you should use numpy to make a matrix. It's a library for just this, and will be about 1000 times faster than a matrix made out of python datastructures, due to its c-level optimizations.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.