Ask Your Question
0

removing the repeated rows of a matrix

asked 2019-08-07 13:54:59 +0100

GA316 gravatar image

My sage program outputs a matrix with integer entries in which some rows are repeated. But I want to remove the multiple entries of rows in the output. Kindly somebody explains to me how to do this.

Thank you.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-08-08 06:14:31 +0100

dsejas gravatar image

updated 2019-08-09 00:58:18 +0100

Hello, @GA316. There are two ways to do this, depending on whether you want to do it manually or automatically.

To remove rows manually, you just need to use the delete_rows method: Suppose you have a matrix A such that its 3rd, 5th and 6th rows are exactly the same as the first row, so they should be removed. Just execute:

A.delete_rows([3, 5, 6])

If you want to do it automatically, the following piece of code can help you:

def remove_repeated_rows(A):
    nr = A.nrows()# number of rows
    eliminate = []# this will store the numbers of the rows to eliminate

    for i in range (nr-1):# check all rows, except the last one
        for j in range(i+1, nr):# compare to the rows below row i
            if A[i] == A[j]:    eliminate.append(j)# if row j equals row i, list j to eliminate

    return A.delete_rows(eliminate)# eliminate the listed rows and return the resulting submatrix

I hope this helps!

edit flag offensive delete link more

Comments

This is a great answer and it works perfectly. Thanks for your valuable time.

GA316 gravatar imageGA316 ( 2019-08-08 08:11:29 +0100 )edit

Happy to help!

dsejas gravatar imagedsejas ( 2019-08-09 08:43:20 +0100 )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

1 follower

Stats

Asked: 2019-08-07 13:54:59 +0100

Seen: 1,090 times

Last updated: Aug 09 '19