1

I am writing a program to check if a matrix is square (The number of rows and columns are equal ex: 2x2, 3x3, etc)

I thought it would be best to count the elements using the built in size function and take the square root. I want to write an if statement where if the square root does not result in a whole number it prints an error statement, but I'm not sure how to specify a whole number in my statement.

here is what I've tried

    import numpy as np
    A = np.array([[1,2,3],[4,5,6]])
    check = A.size
    if check**.5 ...

and I don't know what to put in the rest of the statement

3
  • To check if a value is a whole number, you can use x % 1 == 0, but this approach will fail for checking for square arrays. For example, a matrix of size (18, 2) will return True if you check that the square root of its size is an integer. Commented Jul 19, 2019 at 16:55
  • Taking the square root of the size is needlessly complex. Commented Jul 19, 2019 at 16:55
  • Possible duplicate of Check if a matrix is square? (Python) Commented Jul 19, 2019 at 17:03

2 Answers 2

3

The shape attribute is probably what you want to check.

if A.shape[0] == A.shape[1]:
    # Is square
else:
    # Is not square
Sign up to request clarification or add additional context in comments.

Comments

1

You could check if it's an integer.

if check**.5 == int(check**.5):
    ...

5 Comments

This is a bad idea in general; for certain large near-squares, this check will return true due to floating-point precision issues.
Granted, the best solution to the problem is provided to Jmonsky. Although I often feel that SO answers questions that weren't asked. OP wanted to know how to check if it's a whole number.
And like I said, this is not a good way to do that, because floating-point values have limited precision. Consider x = 99999999; y = ((x+1)*(x-1))**.5. x**2 != (x+1)*(x-1), but y == int(y).
I fold, if OP constructs a 99999999x99999999 dimensional matrix this solution will not work.
I didn't downvote because in the context of the question, it's probably OK, but I wouldn't rule out the existence of smaller, less-square matrices that give the same false positive.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.