David Richmond - 2 years ago 71
Python Question

# How to create a row that displays the counts of column entries in a matrix using python/sage?

so here is my matrix:

``````A = matrix([[1,1,2,2,2],
[3,1,4,3,3],
[0,4,2,4,0],
[0,0,2,0,0],
[0,0,2,0,0]])
``````

I would like to insert a 0 row that displays the number of column entries.

This was my original code:

``````A = matrix([[1,1,2,2,2],
[3,1,4,3,3],
[0,4,2,4,0],
[0,0,2,0,0],
[0,0,2,0,0]])
puzzle = A.insert_row(0, sum(A))
``````

Whats wrong with this code is that it gives me the sum of each column, when I just need the count of each column.

What I have

``````[ 4  6 12  9  5]
[ 1  1  2  2  2]
[ 3  1  4  3  3]
[ 0  4  2  4  0]
[ 0  0  2  0  0]
[ 0  0  2  0  0]
``````

Desired

``````[ 2  3  5  3  2]
[ 1  1  2  2  2]
[ 3  1  4  3  3]
[ 0  4  2  4  0]
[ 0  0  2  0  0]
[ 0  0  2  0  0]
``````

Best,

David

Try the `nonzero_positions_in_column` method:

``````sage: A = matrix([[1,1,2,2,2],
....:             [3,1,4,3,3],
....:             [0,4,2,4,0],
....:             [0,0,2,0,0],
....:             [0,0,2,0,0]])
sage: A.column(1)
(1, 1, 4, 0, 0)
sage: A.nonzero_positions_in_column(1)
[0, 1, 2]

sage: v = vector([len(A.nonzero_positions_in_column(i)) for i in range(A.ncols())])
sage: A.insert_row(0, v)
[2 3 5 3 2]
[1 1 2 2 2]
[3 1 4 3 3]
[0 4 2 4 0]
[0 0 2 0 0]
[0 0 2 0 0]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download