# Count number of ones in a set of matrix [closed]

I am having the following code:

v = MatrixSpace(GF(2),2,2)
c = *2
for vv in v.list():
t=sum(vv)
c = [x+y for x,y in zip(c,t)]
print c


My goal is to count how many '1s' that I have for each column within the set of matrices. For example with the first 4 matrices in the set:

[0 0]  [1 0]  [0 1]  [0 0]
[0 0], [0 0], [0 0], [1 0]


I expect to receive [2,1] as a result, i.e. there are 2 of '1s' appear in the 1st column and 1 of '1s' appears in the 2nd column. However, I got [0, 1], because it's binary base.

Thank you for reading my problem and support :)

edit retag reopen merge delete

### Closed for the following reason the question is answered, right answer was accepted by imnvsh close date 2019-03-01 04:28:18.279600

Sort by » oldest newest most voted

Building on @FrédéricC's comment.

If a is an element in GF(2), a.lift() is the corresponding element in ZZ. Using .lift() makes it so that 1 + 1 will be computed in ZZ and give 2 instead of being computed in GF(2) and give 0.

If a is a matrix over GF(2), a.lift() is the corresponding matrix over ZZ.

The rows of a can be summed using sum(a).

Define the matrix space:

sage: M = MatrixSpace(GF(2), 2, 2)


List its elements:

sage: M.list()
[
[0 0]  [1 0]  [0 1]  [0 0]  [0 0]  [1 1]  [1 0]  [1 0]
[0 0], [0 0], [0 0], [1 0], [0 1], [0 0], [1 0], [0 1],

[0 1]  [0 1]  [0 0]  [1 1]  [1 1]  [1 0]  [0 1]  [1 1]
[1 0], [0 1], [1 1], [1 0], [0 1], [1 1], [1 1], [1 1]
]


How many 1's in each column of each matrix in M:

sage: [sum(a.lift()) for a in M]
[(0, 0),
(1, 0),
(0, 1),
(1, 0),
(0, 1),
(1, 1),
(2, 0),
(1, 1),
(1, 1),
(0, 2),
(1, 1),
(2, 1),
(1, 2),
(2, 1),
(1, 2),
(2, 2)]


Sum over all matrices in M:

sage: sum(sum(a.lift()) for a in M)
(16, 16)

more As mentioned in the comments you can do a lift.

For vectors you can also change the ring to the integers, to lift all the entries. For example,

def ones_per_column(matrices):
return sum(vector(sum(c.change_ring(ZZ)) for c in m.columns()) for m in matrices)


Maybe more efficiently, change the ring of each matrix to the integers, add them and take the column sums:

def ones_per_column(matrices):
return vector(sum(c) for c in sum(m.change_ring(ZZ) for m in matrices).columns())


In either case you can do

sage: ones_per_column(list(MatrixSpace(GF(2), 2, 2))[0:4])
(2, 1)

more