Home > OS >  How to find the mirror of an identity matrix without using numpy?
How to find the mirror of an identity matrix without using numpy?

Time:09-23

Here I have an identity matrix that goes from top left to bottom right. I'm trying to flip it so I can get a row of 1's going from top right to bottom left but I don't want to use numpy. But I just cant work out how to do it...

num = int(input("enter your number"))
for i in range(0, num):
    for j in range(0, num):
        if (i == j):
            print(1, sep=" ", end=" ")
        else:
            print(0, sep=" ", end=" ")
    print()

Example:
Input: 4
Output:

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

CodePudding user response:

There is simple relation between column, row and num

if i   j   1 == num:

Full code:

num = int(input("enter your number"))
for i in range(0, num):
    for j in range(0, num):
        if i   j   1 == num:
            print(1, sep=" ", end=" ")
        else:
            print(0, sep=" ", end=" ")
    print()

EDIT:

Other idea is to revers one range

for j in range(num-1, -1, -1):

Full code:

num = int(input("enter your number"))
for i in range(0, num):
    for j in range(num-1, -1, -1):
        if i == j:
            print(1, sep=" ", end=" ")
        else:
            print(0, sep=" ", end=" ")
    print()

CodePudding user response:

To create an anti-diagonal matrix, put a 1 in every (row, column) where column = n-1 - row:

def anti_diagonal(n):
    """Return the n x n antidiagonal matrix as a list of lists. """
    return [ [ 0 if column != n-1 - row else 1 for column in range(n) 
             ] for row in range(n) ]
  • Related