First time here? Check out the FAQ!

Ask Your Question
0

removing the repeated rows of a matrix

asked 5 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 5 years ago

dsejas gravatar image

updated 5 years ago

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!

Preview: (hide)
link

Comments

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

GA316 gravatar imageGA316 ( 5 years ago )

Happy to help!

dsejas gravatar imagedsejas ( 5 years ago )

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: 5 years ago

Seen: 1,275 times

Last updated: Aug 09 '19