Ask Your Question
1

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

asked 2016-11-09 12:27:10 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

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 amount of row entries in each column.

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]
edit retag flag offensive close merge delete

Comments

1 Answer

Sort by ยป oldest newest most voted
2

answered 2016-11-09 22:38:04 +0200

calc314 gravatar image

Here is an option:

r=[Integer(len(A.nonzero_positions_in_column(j))) for j in range(A.dimensions()[1])]
A.insert_row(0, r)
edit flag offensive delete link more

Comments

Nice solution. You could replace A.dimensions()[1]) by A.ncols().

slelievre gravatar imageslelievre ( 2016-11-10 10:50:18 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2016-11-09 12:27:10 +0200

Seen: 354 times

Last updated: Nov 09 '16